net learning

Upload: 187190

Post on 04-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 .Net Learning

    1/22

    Class

    The most common definition states that a class is a template for an object. Suppose thatsomeone builds a paper pattern for a shirt. All the shirts done with the same paper pattern

    will be identical (same design, size, etc.). In this sample, the paper pattern is the class and

    the shirt is the object. To build the same exact shirt over and over, you need the paper

    pattern as a template. Another great example are house plans and blueprints. The plansand blueprints define the number of rooms, the size of the kitchen, the number of floors,

    and more. In this real world sample, the house plans and blueprints are the class and thehouse is the object. In OOP you program a class as a template for a specific object orgroups ob objects that will always have the same features.

    Class members

    A class has different members, and developers in Microsoft suggest to program them in thefollowing order:

    Namespace: The namespace is a keyword that defines a distinctive name or last

    name for the class. A namespace categorizes and organizes the library (assembly)where the class belongs and avoids collisions with classes that share the same name.

    Classdeclaration: Line of code where the class name and type are defined.

    Fields: Set of variables declared in a class block.

    Constants: Set of constants declared in a class block. Constructors: A method or group of methods that contains code to initialize the

    class.

    Properties: The set of descriptive data of an object.

    Events: Program responses that get fired after a user or application action.

    Methods: Set of functions of the class.

    Destructor: A method that is called when the class is destroyed. In managed code,

    the Garbage Collector is in charge of destroying objects; however, in some casesdevelopers need to take extra actions when objects are being released, such asfreeing handles or deallocating unmanaged objects. In .NET, there is no concept of

    deterministic destructors. The Garbage Collector will call the Finalize() method at anon-deterministic time while reclaiming memory for the application.

    Access keywords

    Access keywords define the access to class members from the same class and from otherclasses. The most common access keywords are:

    Public: Allows access to the class member from any other class.

    Private: Allows access to the class member only in the same class.

    Protected: Allows access to the class member only within the same class and from

    inherited classes. Internal: Allows access to the class member only in the same assembly.

    Protected internal: Allows access to the class member only within the same class,

    from inherited classes, and other classes in the same assembly. Static: Indicates that the member can be called without first instantiating the class.

  • 8/13/2019 .Net Learning

    2/22

    usingSystem;

    ///Namespace: Consider using CompanyName.Product.ComponentType

    namespaceDotNetTreats.OOSE.OOP_CSharp

    {

    ///Class declaration

    publicclassemployee

    {

    ///Fields

    privatestring_name;

    privateint_salary;

    ///Constants

    privateconstintanualBonus = 1000;

    ///Constructor

    publicemployee()

    {

    }

    ///Properties

    publicstringName

    {

    get

    {

    return_name;

    }

    set

    {

    _name = value;}

    }

    publicintSalary

    {

    get

    {

    return_salary;

    }

    set

    {

    _salary = value;}

    }

    ///Event handlers

    publiceventEventHandler OnPromotion

    {

    add

    {

  • 8/13/2019 .Net Learning

    3/22

    }

    remove

    {

    }

    }

    ///MethodspublicvoidDuplicateSalary()

    {

    _salary = _salary*2;

    }

    }

    }

    Encapsulation

    What is encapsulation? Well, in a nutshell, encapsulation is thehiding of data implementation by restricting access to accessors and

    mutators. First, lets define accessors and mutators:

    AccessorAn accessor is a method that is used to ask an object about itself. InOOP, these are usually in the form of properties, which have, undernormal conditions, agetmethod, which is an accessor method.However, accessor methods are not restricted to properties and can beany public method that gives information about the state of the object.

    PublicClassPerson We use Private here to hide the implementation of the objects

    fullName, which is used for the internal implementation of Person.Private_fullNameAsString= Raymond Lewallen

    This property acts as an accessor. To the caller, it hides the implementation of fullName and where it is set and what is setting its value. It only returnsthe fullname state of the Person object, and nothing more. From another class, calling Person.FullName() will return Raymond Lewallen. There are other things, such as we need to instantiate the Person class first, but thats a different discussion.

  • 8/13/2019 .Net Learning

    4/22

    PublicReadOnlyPropertyFullName()AsStringGet

    Return_fullNameEndGet

    EndProperty

    EndClass

    MutatorMutators are public methods that are used to modifythe state of an object, while hiding the implementation of exactly howthe data gets modified. Mutators are commonly another portion of theproperty discussed above, except this time its thesetmethod that lets the caller modify themember data behind the scenes.

    PublicClassPerson We use Private here to hide the implementation of the objects fullName, which is used for the internal implementation of Person.Private_fullNameAsString= Raymond Lewallen

    This property now acts as an accessor and mutator. We still have hidden the implementation of fullName.PublicPropertyFullName()AsString

    GetReturnFullName

    EndGetSet(ByValvalueAsString)

    _fullName = valueEndSet

    EndProperty

    EndClass

    Ok, now lets look at a different example that contains an accessor and a mutator:

    PublicClassPersonPrivate_fullNameAsString= Raymond Lewallen

    Here is another example of an accessor method, exceptthis time we use a function. PublicFunctionGetFullName()AsString

    Return_fullNameEndFunction

    Here is another example of a mutator method, except this time we use a subroutine.PublicSubSetFullName(ByValnewNameAsString)

    _fullName = newNameEndSub

    EndClass

  • 8/13/2019 .Net Learning

    5/22

    So, the use of mutators and accessors provides many advantages. Byhiding the implementation of our Person class, we can make changes tothe Person class without the worry that we are going to break othercode that is using and calling the Person class for information. If wewanted, we could change the fullName from a String to an array of

    single characters (FYI, this is what a string object actually is behindthe scenes) but they callers would never have to know because we wouldstill return them a single FullName string, but behind the scenes weare dealing with a character array instead of a string object. Itstransparent to the rest of the program. This type of data protectionand implementation protection is calledEncapsulation. Think of accessors and mutators as thepieces that surround the data that forms the class.

    Abstraction

    Data abstraction is the simplest of principles to understand. Data

    abstraction and encapuslation are closely tied together, because asimple definition of data abstraction is the development of classes,objects, types in terms of their interfaces and functionality, insteadof their implementation details. Abstraction denotes a model, a view,or some other focused representation for an actual item. Its thedevelopment of a software object to represent an object we can find inthe real world. Encapsulation hides the details of that implementation.

    Abstractionis used to manage complexity. Software developers use abstraction todecompose complex systems into smaller components. As development

    progresss, programmers know the functionality they can expect from asyet undeveloped subsystems. Thus, programmers are not burdened byconsidering the waysin which the implementation of later subsystesmwill affect the design of earlier development.

    The bestdefinition of abstraction Ive ever read is: An abstraction denotesthe essential characteristics of an object that distinguish it from allother kinds of object and thus provide crisply defined conceptualboundaries, relative to the perspective of the viewer. G. Booch,Object-Oriented Design With Applications, Benjamin/Cummings, Menlo

    Park, California, 1991.

    Lets look at this code for a personobject. What are some things that a person can do? Those things must berepresented here in our software model of a person. Things such as howtall the person is, and the age of the person; we need to be able tosee those. We need the ability for the person to do things, such asrun. We need to be able to ask the person if they can read.

  • 8/13/2019 .Net Learning

    6/22

    PublicClassPerson

    Private_heightAsInt16PublicPropertyHeight()AsInt16

    GetReturn_height

    EndGetSet(ByValValueAsInt16)

    _height = ValueEndSet

    EndProperty

    Private_weightAsInt16PublicPropertyWeight()AsInt16

    GetReturn_weight

    EndGetSet(ByValValueAsInt16)

    _weight = ValueEndSet

    EndProperty

    Private_ageAsInt16PublicPropertyAge()AsInt16

    GetReturn_age

    EndGetSet(ByValValueAsInt16)

    _age = ValueEndSet

    EndProperty

    PublicSubSit()

    Codethat makes the person sitEndSub

    PublicSubRun() Code that makes the person run

    EndSub

    PublicSubCry() Code that make the person cry

    EndSub

    PublicFunctionCanRead()AsBoolean Codethat determines if the person can read

    and returns a true or falseEndFunction

    EndClass

    So, there we have started to create a software model of a personobject; we have created an abstract type of what a person object is tous outside of the software world. The abstract person is defined by theoperations that can be performed on it, and the information we can get

  • 8/13/2019 .Net Learning

    7/22

    from it and give to it. What does the abstracted person object looklike to the software world that doesnt have access to its innerworkings? It looks like this:

    You cant really see what the code is that makes the person run. This isencapsulation that wediscuseed.

    So,in short, data abstraction is nothing more than the implementation ofan object that contains the same essential properties and actions wecan find in the original object we are representing.

    Inheritance

    Now lets discuss inheritance. Objects can relate to eachotherwith either a has a, uses a or an is a relationship. Is ais the inheritance way of object relationship. The example ofthis that has always stuck with me over the years is a library (I thinkI may have read it in something Grady Booch wrote). So, take alibrary, for example. A library lends more than just books, italso lends magazines, audiocassettes and microfilm. On somelevel, all of these items can be treated the same: All four typesrepresent assets of the library that can be loaned out to people.However, even though the 4 types can be viewed as the same, they arenot identical. A book has an ISBN and a magazine does not.And audiocassette has a play length and microfilm cannot be checked outovernight.

    Each of these librarys assets should be represented by its ownclass definition. Without inheritance though, each class mustindependently implement the characteristics that are common to allloanable assets. All assets are either checked out or availablefor checkout. All assets have a title, a date of acquisition anda replacement cost. Rather than duplicate functionality,inheritance allows you to inherit functionality from another class,called asuperclassor base class.

    Let us look at loanable assets base class. This will be usedas the base for assets classes such as book and audiocassette:

    PublicClassLibraryAsset

    Private_titleAsStringPublicPropertyTitle()AsString

    GetReturn_title

    EndGet

  • 8/13/2019 .Net Learning

    8/22

    Set(ByValValueAsString)_title = Value

    EndSetEndProperty

    Private_checkedOutAsBooleanPublicPropertyCheckedOut()AsBoolean

    GetReturn_checkedOut

    EndGetSet(ByValValueAsBoolean)

    _checkedOut = ValueEndSet

    EndProperty

    Private_dateOfAcquisitionAsDateTimePublicPropertyDateOfAcquisition()AsDateTime

    GetReturn_dateOfAcquisition

    EndGetSet(ByValValueAsDateTime)

    _dateOfAcquisition = ValueEndSet

    EndProperty

    Private_replacementCostAsDoublePublicPropertyReplacementCost()AsDouble

    GetReturn_replacementCost

    EndGetSet(ByValValueAsDouble)

    _replacementCost = ValueEndSet

    EndProperty

    EndClass

    This LibraryAsset is a superclass, or base class, that maintainsonly the data and methods that are common to all loanable assets.Book, magazine, audiocassette and microfilm will all besubclassesor derived classesor the LibraryAsset class, and so they inherit thesecharacteristics. The inheritance relationship is called the isa relationship. A book is a LibraryAsset, as are the other 3assets.

    Lets look atbook and audiocassette classes that inherit from out LibraryAsset class:

    PublicClassBookInheritsLibraryAsset

    Private_authorAsStringPublicPropertyAuthor()AsString

    GetReturn_author

  • 8/13/2019 .Net Learning

    9/22

    EndGetSet(ByValValueAsString)

    _author = ValueEndSet

    EndProperty

    Private_isbnAsStringPublicPropertyIsbn()AsString

    GetReturn_isbn

    EndGetSet(ByValValueAsString)

    _isbn = ValueEndSet

    EndProperty

    EndClass

    PublicClassAudioCassetteInheritsLibraryAsset

    Private_playLengthAsInt16PublicPropertyPlayLength()AsInt16

    GetReturn_playLength

    EndGetSet(ByValValueAsInt16)

    _playLength = ValueEndSet

    EndProperty

    EndClass

    Now, lets create an instance of the book class so we can record a new book into the libraryinventory:

    DimmyBookAsBook = NewBookmyBook.Author = Sahil MalikmyBook.CheckedOut = FalsemyBook.DateOfAcquisition = #2/15/2005#myBook.Isbn = 0-316-63945-8myBook.ReplacementCost = 59.99myBook.Title = The Best Ado.Net Book Youll Ever Buy

    You see, when we create a new book, we have all the properties of

    the LibraryAsset class available to us as well, because we inheritedthe class. Methods can be inherited as well. Lets add afew methods to our LibraryAsset class:

    PublicClassLibraryAsset

    Pretend the properties listed above are right here

    PublicSubCheckOut()

  • 8/13/2019 .Net Learning

    10/22

    IfNot_checkedOut Then_checkedOut = TrueEndSub

    PublicSubCheckIn()If_checkedOut Then_checkedOut = False

    EndSub

    EndClass

    Now, our myBook we created above automatically inherited thesemethods, and we didnt even have to touch the Book class in order forit to happen. The book and audiocassette classes aboveautomatically inherited the abilities to be checked out and checkedin. In our myBook above, now we can check the book out bycalling myBook.CheckOut(). Simple! One of the mostpowerful features of inheritance is the ability to extend componentswithout any knowledge of the way in which a class was implemented.

    Declaration options, such as Public and Private, dictate whichmembers of a superclass can be inherited. For more information onthis, see the Declaration Option section ofErics post.

    Polymorphism

    Polymorphism means one name, many forms. Polymorphismmanifests itself by having multiple methods all with the same name, butslighty different functionality. Many VB6ers are familiarwith interface polymorphism. Im only going to discusspolymorphism from the point of view of inheritance because this is thepart that is new to many people. Because of this, it can bedifficult to fully grasp the full potential of polymorphism until youget some practice with it and see exactly what happens under differentscenarios. Wereonly going to talk about polymorphism, likethe other topics, at the basic level.

    There are 2 basic types of polymorphism. Overridding, alsocalled run-time polymorphism, and overloading, which is referred to ascompile-time polymorphism. This difference is, for methodoverloading, the compiler determines which method will beexecuted, and this decision is made when the code gets compiled.

    Which method will be used for method overriding is determined atruntime based on the dynamic type of an object.

    Lets look at some code:

    Base class for library assetsPublicMustInheritClassLibraryAsset

    http://codebetter.com/blogs/eric.wise/archive/2005/02/14/50919.aspxhttp://codebetter.com/blogs/eric.wise/archive/2005/02/14/50919.aspxhttp://codebetter.com/blogs/eric.wise/archive/2005/02/14/50919.aspxhttp://codebetter.com/blogs/eric.wise/archive/2005/02/14/50919.aspx
  • 8/13/2019 .Net Learning

    11/22

    Default fine per day for overdue itemsPrivateConst_finePerDayAsDouble= 1.25

    Due date for an item that has been checked out Private_dueDateAsDateTimePublicPropertyDueDate()AsDateTime

    GetReturn_dueDate

    EndGetSet(ByValValueAsDateTime)

    _dueDate = ValueEndSet

    EndProperty

    Calculates the default fine amount for an overdue itemPublicOverridableFunctionCalculateFineTotal()AsDouble

    DimdaysOverdueAsInt32 = CalculateDaysOverdue()IfdaysOverdue > 0 Then

    ReturndaysOverdue * _finePerDayElse

    Return0.0EndIf

    EndFunction

    Calculates how many days overdue for an item being return edProtectedFunctionCalculateDaysOverdue()AsInt32

    ReturnDateDiff(DateInterval.Day, _dueDate, DateTime.Now())EndFunction

    EndClass

    Magazine class that inherits LibraryAssetPublicNotInheritableClassMagazine

    InheritsLibraryAsset

    EndClass

    Book class that inherits LibraryAssetPublicNotInheritableClassBook

    InheritsLibraryAsset

    This is morphing the CalculateFineTotal() function of the base class. This function overrides the base class function, and any call to CalculateFineTotal from any instantiated Book class will use this function, not the base class function. This type of polymorphism is called overriding.

    PublicOverridesFunctionCalculateFineTotal()AsDoubleDimdaysOverdueAsInt32 = CalculateDaysOverdue()IfdaysOverdue > 0 Then

    ReturndaysOverdue * 0.75Else

    Return0.0EndIf

    EndFunction

    EndClass

  • 8/13/2019 .Net Learning

    12/22

    AudioCassette class that inherits LibraryAssetPublicNotInheritableClassAudioCassette

    InheritsLibraryAsset

    This is morphing the CalculateFineTotal() function of the base class. This is morphing the CalculateFineTotal(double) function of the audiocassette class. This function overrides the base class function, and any call to CalculateFineTotal() from any instantiated AudioCassette Class will use this function, not the base class function. This type of polymorphism is called overloading and overriding.PublicOverloadsOverridesFunctionCalculateFineTotal()AsDouble

    DimdaysOverdueAsInt32 = CalculateDaysOverdue()IfdaysOverdue > 0 Then

    ReturndaysOverdue * 0.25Else

    Return0.0EndIf

    EndFunction

    This is morphing the CalculateFineTotal() function of the audiocassette class. This type of polymorphism is called overloading.PublicOverloadsFunctionCalculateFineTotal(ByValfinePerDayAsDouble)AsDouble

    DimdaysOverdueAsInt32 = CalculateDaysOverdue()IfdaysOverdue > 0AndAlsofinePerDay > 0.0 Then

    ReturndaysOverdue * finePerDayElse

    Return0.0EndIf

    EndFunctionEndClass

    You see our library asset class. Pay attention to theoverridable function CalculateFineTotal(). In LibraryAsset, wehave defined the default functionality for this method that any derivedclasses can use. Any class derived from LibraryAsset can use thisdefault behavior and calculate fines based on the defaultimplementation of $1.25 per day late. This is true for ourMagazine class. We didnt override the function so when late feesare calculated for late magazine returns, it will use the defaultimplementation.

    Now look at the book class. We have overridden theCalculateFineTotal to use a different value when determining latefees. The overrides keywork in VB tells the caller that anymethod call will use the virtual method found in Book, not the defaultimplementation found in LibraryAsset. We have implemented runtimepolymorphismmethod overriding.

  • 8/13/2019 .Net Learning

    13/22

    Lets move on to AudioCassette. Here we have the same methodoverriding we found in the book class. Fines are calculated basedon $0.25 per day. Notice weve added something extra. Weveadded the Overloads keywork to our function and to a new function withthe same name, except the new function now accepts a parameter.

    Now the caller can call either method, and depending on whether or nota parameter is passed, that determines with method will beexecuted. Notice we do not include the overrides keywork in the2nd function with a parameter. This is because not method existsin LibraryAsset with that same signature (accepting a parameter of typedouble). You can only override methods with the same signature ina base class.

    Now lets look at some code that creates all these library items andchecks them in and cacluates our fines based on returning them 3 dayslate:

    PublicClassDemo

    PublicSubGo() Set the due date to be three days ago DimdueDateAsDateTime = DateAdd(DateInterval.Day, -3, Now())ReturnMagazine(dueDate)ReturnBook(dueDate)ReturnAudioCassette(dueDate)

    EndSub

    PublicSubReturnMagazine(ByValdueDateAsDateTime)DimmyMagazineAsLibraryAsset = NewMagazine

    myMagazine.DueDate = dueDateDimamountDueAsDouble= myMagazine.CalculateFineTotal()Console.WriteLine(Magazine: {0}, amountDue.ToString())

    EndSub

    PublicSubReturnBook(ByValdueDateAsDateTime)DimmyBookAsLibraryAsset = NewBookmyBook.DueDate = dueDateDimamountDueAsDouble= myBook.CalculateFineTotal()Console.WriteLine(Book: {0}, amountDue.ToString())

    EndSub

    PublicSubReturnAudioCassette(ByValdueDateAsDateTime)DimmyAudioCassetteAsAudioCassette = NewAudioCassettemyAudioCassette.DueDate = dueDateDimamountDueAsDoubleamountDue = myAudioCassette.CalculateFineTotal()Console.WriteLine(AudioCassette1: {0}, amountDue.ToString())amountDue = myAudioCassette.CalculateFineTotal(3.0)Console.WriteLine(AudioCassette2: {0}, amountDue.ToString())

    EndSub

    EndClass

  • 8/13/2019 .Net Learning

    14/22

    The output will look like the following:

    Magazine: 3.75Book: 2.25AudioCassette1: 0.75

    AudioCassette2: 9

    You can see how all of our output was different, based on the methodthat was executed. We created a new Magazine, which is a type ofLibraryAsset. That is why the instantiation says myMagazine AsLibraryAsset. However, since we actually want a magazine, wecreate a New Magazine. Same thing with book. For Book,its a little bit more tricky. Since we created a Book of the typeLibraryAsset, this is where the polymorphism comes into play.Book overrides the CalculateFineTotal of LibraryAsset.Audiocassette is a little bit different. It actually extends the

    implementation of LibraryAsset by including an overloaded function forCalculateFineTotal(). If we werent going to use the functionthat took a parameter, we would create it the same way we created theBook and Magazine classes. But in order to use the overloadedfunction, we have to create a new AudioCassette of the typeAudioCassette, because LibraryAsset doesnt support the overloadedfunction.

    Only the Magazine used the default method found in the baseclass. Book and AudioCassette used their own implementations ofthe method. Also, at compile time, the decision was made which

    method would be used when we calculate amountDue for the AudioCassetteclass. The first call used the 1st method in AudioCassettewithout parameters. The 2nd call used the 2nd method with aparameter.

    There is an important question that several people ask in forums and the question is "so

    what's the difference between structure and class? "Or "In what could be the structureuseful as we have already the class that can do perfectly the job?" Those questions could

    particularly be posed by a java programmer who wants to emigrate from Java to .Net. For

    this reason I will enumerate through this article some of those differences to make clear theissue.

  • 8/13/2019 .Net Learning

    15/22

    1. The structures are value types and the classes are reference types. Before stepping

    to the next point let explain the difference between the two types. Imagine this is

    the memory within the machine

    Figure 1

    The value types are stocked in the stack but the reference type no. In fact, whatcould be really stocked in the stack for the reference types is a pointer that targetsan address at the heap level.

    Then type of structure objects are stocked in the stack exactly like any value typesay an Integer, a double or a float. Meanwhile, memory emplacements could be

    reserved for the reference types in the heap. Defining heap and stack and the

    difference between them is beyond the scope of this article but nevertheless Ipropose this excellent Matthew article to understand the memory mechanism.

    http://www.c-

    sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91

    2. Classes are usually used for large amounts of data, whereas structs are usually used

    for smaller amount of data3. Classes could be inherited whereas structures no

    4. A structure couldn't be Null like a class5. A structure couldn't have a destructor such as class

    6. A structure can't be abstract, a class can

    7. You cannot override any methods within a structure except those belong to type ofobject

    o Equals()

    o GetHashCode()o GetType()o ToString()

    And the other polymorphism technique used for structures is implementing interfaces

    http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91
  • 8/13/2019 .Net Learning

    16/22

    8. Declared events within a class are automatically locked and then they are Thread

    safe, at the contrast of the structure type where event couldn't be locked.

    9. A structure must have always the default parameter less constructor be defined aspublic but a class might have one, so you can't define a private parameter less

    constructor

    structMe{

    privateMe()// compile-time error{

    }

    }

    classMe

    {privateMe()// runs Ok{

    }

    10.A static constructor is trigged in case of class but not in case of structure

    structmyStructure

    {staticmyStructure(){

    Console.WriteLine("This is me a structure");

    }}classmyClass

    {staticmyClass()

    {Console.WriteLine("This is me a class");

    }}

    classProgram{

    staticvoidMain(string[] args){

    myStructures = newmyStructure();//Nothing happenmyClassc = newmyClass();//Will out put This is me a class

    Console.Read();}

    }

    11.The strucutre can't conatain a volatile field wheatheas the class does

    12.You can't use sizeof with classes but you can with structures

  • 8/13/2019 .Net Learning

    17/22

    13.Fields are automatically initialized with classes to 0/false/null wheatheras in

    strucutres no

    14.Fields couldn't directley instanciated within structures but classes allow suchoperations

    structmyStructure

    {publicstringx = 2;//Not allowed

    }classmyClass

    {

    publicstringx = 2;//Allowed}

    15.Structure and class don't adopt the same aproach taward theSystem.Object.Equals() method

    Suppose those Strucutre and class

    structStructurePerson{

    publicstringFirstName;publicstringLastName;

    }

    classClassPerson

    {publicstringFirstName;publicstringLastName;

    }

    Now, try this code

    classProgram

    {

    staticvoidMain(string[] args){

    StructurePersonstrX = newStructurePerson();

    strX.LastName = "Bejaoui";

    strX.FirstName = "Bechir";StructurePersonstrY = newStructurePerson();strY.LastName = "Bejaoui";

    strY.FirstName = "Bechir";

    if(strX.Equals(strY)){Console.WriteLine("strX = strY");

    }else{

    Console.WriteLine("strX != strY");}//This code displays strX = strY

  • 8/13/2019 .Net Learning

    18/22

    ClassPersonclsX = newClassPerson();clsX.LastName = "Bejaoui";clsX.FirstName = "Bechir";ClassPersonclsY = newClassPerson();clsY.LastName = "Bejaoui";

    clsY.FirstName = "Bechir";

    if(clsX.Equals(clsY)){

    Console.WriteLine("clsX = clsY");}else{

    Console.WriteLine("clsX != clsY");}//This code displays clsX != clsYConsole.Read();

    }}

    In the first strucutre case the two objects are value types, they are compared according totheir values like int I = 5 and int J = 5 so I=J because they have the same value. At thecontrast, in the class case two different and distinct reference are created so to make clsX= clsY you should use this code.

    ClassPersonclsX = newClassPerson();clsX.LastName = "Bejaoui";clsX.FirstName = "Bechir";ClassPersonclsY = clsX;if(clsX.Equals(clsY)){

    Console.WriteLine("clsX = clsY");}else{

    Console.WriteLine("clsX != clsY");

    }//This code displays clsX = clsY

    Inheritance

    Inheritance is a powerful feature of Object Oriented Programming languages. Usinginheritance you create base classes that encapsulate common functionality. The base class

    is inherited by derived classes. The derived classes inherit the properties and methods of

  • 8/13/2019 .Net Learning

    19/22

    the base class. The .Net Framework uses inheritance throughout. For example, the

    CollectionBase class contains properties and methods required by most collections. It

    contains properties such as Capacity and Count and methods such as Clear and RemoveAt.

    In order to use the base class in another class (referred to as the derived class) youreference the base class by placing a colon after the name of the derived class and then

    place the name of the base class. The following code defines a base class RentalItem andtwo derived classes DVD and Book that inherit the base class.

    publicclassRentalItem

    {string_title;

    publicstringTitle

    {

    get{ return_title; }set{ _title = value; }

    }publicBooleanCheckStock(stringtitle)

    {//code to check if in stock.

    //returns true for demo.returntrue;

    }

    }

    publicclassDVD: RentalItem

    {

    }publicclassBook: RentalItem

    {

    }

    The derived classes inherit the base class's properties and methods and clients of the

    derived class have no knowledge of the base class. The derived class is not limited to theproperties and methods of the base class. They can further define properties and methodsas needed. The following code shows the derived class Book defining its own property ISBN.

    publicclassBook: RentalItem{

    string_ISBN;

    publicstringISBN

    {get{ return_ISBN; }

    set{ _ISBN = value; }}

    }

    Clients of the Book class will be exposed to both properties Title and ISBN as shown in the

  • 8/13/2019 .Net Learning

    20/22

    following screen shot.

    There are many times when the derived class needs to use the functionality of the base

    class but also needs to add some functionality unique to the derived class. In this case thederived DVD class uses the keyword base to call the base class RentalItem's CheckStockmethod as shown in the following code.

    publicclassDVD: RentalItem{

    publicBooleanRent(stringtitle, intage)

    {if(base.CheckStock(title)){

    //code to check rating against age of renter//returns true for demoreturntrue;

    }else{

    returnfalse;

    }}

    }

    Methods inherited by the derived class can be overloaded just as you would overload anymethod in the same class. The method names are the same but the method signatures aredifferent. The following code shows the Book class overloading the CheckStock method of

    the RentalItem base class.

    publicclassBook: RentalItem

    {

    string_ISBN;

    publicstringISBN

    {get{ return_ISBN; }

    set{ _ISBN = value; }

  • 8/13/2019 .Net Learning

    21/22

    }

    publicBooleanCheckStock(stringtitle, stringauthor)

    {//code to check if in stock.

    //returns true for demo.returntrue;

    }}

    A client of the Book class will see both methods as shown in the following screen shot.

    A method of the derived class can override a method of the base class using the override

    key word. For example the Book class can override the CheckStock method of the

    RentalItem base class to pass in the ISBN instead of the title.

    publicoverrideBooleanCheckStock(stringISBN){

    //code to check if in stock.//returns true for demo.

    returntrue;

    }

    In this case clients of the Book class could use the overridden method and would not see

    the RentalItem's method.

    At this point, a client can instantiate an instance of both the Book class and the RentalItemclass. There are times when the base class is not designed to be instantiated directly byclients; rather it is designed to be inherited by derived classes that are then exposed to

    clients. These types of base classes are called abstract classes. To create abstract classes

    use the abstract key word when defining the base class.

    publicabstractclassRentalItem

    {string_title;

    publicstringTitle{

    get{ return_title; }set{ _title = value; }

    }publicBooleanCheckStock(stringtitle){

    //code to check if in stock.

  • 8/13/2019 .Net Learning

    22/22

    //returns true for demo.

    returntrue;

    }}

    The .Net Framework contains many abstract classes, for example the TextReader class is

    the abstract base class of the StreamReader and StringReader classes.

    In this article you looked at inheritance and how it is used in C# programming. It isimportant that you understand this concept to efficiently program in C# and effectively work

    with the .NET framework. For more information on object oriented programming, C#, and

    working with the .NET framework refer to my book "Beginning C# Object OrientedProgramming" from Apress publishers.