c# notes.docx

Upload: praveen-chand

Post on 24-Feb-2018

238 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/24/2019 C# Notes.docx

    1/82

    .Net Basics & C#:.Net Program Execution:

    Let us now understand, how a .Net program executes. Using dotnet we cancreate diferent types o applications. A ew o the common types o .NET

    applications include We, Windows, !onsole and "oile Applications. #rrespecti$eo the type o the application, when you execute any .NET application theollowing happens

    %. The .NET application gets compiled into #ntermediate language L'. #L is alsoreerred as !ommon #ntermediate language &!#L' and "icrosot #ntermediatelanguage &"(#L'. )oth .NET and non .NET applications generate an assemly.Assemlies ha$e an extension o .*LL or .E+E. or example i you compile awindows or !onsole application, you get a .E+E, where as when we compile awe or !lass lirary pro-ect we get a .*LL. The diference etween a .NET andNN .NET assemly is that, *TNET Assemly is in intermediate languageormat where as NN *TNET assemly is in nati$e code ormat.

    /. NN *TNET applications can run directly on top o the operating system,where as *TNET applications run on top o a $irtual en$ironment called as!ommon Language 0untime &!L0'. !L0 contains a component called 1ust #n2Time!ompiler &1#T', which will con$ert the #ntermediate language into nati$e codewhich the underlying operating system can understand.(o, in .NET the application execution consists o / steps%. Language compiler, compiles the (ource !ode into #ntermediate Language L'

    /. 1#T compiler in !L0 con$erts, the #L into nati$e code which can then e run onthe underlying operating system.

    (ince, a .NET assemly is in #ntermedaite Language ormat and not nati$ecode, .NET assemlies are portale to any platorm, as long as the targetplatorm has the !ommon Language 0untime &!L0'. The target platorm3s !L0con$erts the #ntermedaite Language into nati$e code that the underlyingoperating system can understand. #ntermediate Languge is also called asmanaged code. This is ecause !L0 manages the code that runs inside it. orexample, in a 4)5 program, the de$eloper is responsile or de2allocating thememory consumed y an o-ect. # a programmer orgets to de2allocate memory,we may run into hard to detecct out o memory exceptions. n the other hand

    a .NET programmer need not worry aout de2allocating the memory consumedy an o-ect. Automatic memory management, also 6nown as graage collectionis pro$ided y !L0. Apart, rom garage collection, there are se$eral otherene7ts pro$ided y the !L0, which we will discuss in a later session. (ince, !L0is managing and executing the #ntermediate Language, it L' is also called asmanaged code.

    ILDASM and ILASM

    To ee! inside an assem"$ %it ILDASM 'oo% tese stes.

    (.Na$igate to 4isual (tudio !ommand 8rompt &(tart 29 All 8rograms 29"icrosot 4isual (tudio /:%: 29 4isual (tudio Tools 29 0ight !lic6 on 4isual (tudio

  • 7/24/2019 C# Notes.docx

    2/82

    !ommand 8rompt /:%/ and select ;0un as Administrator;').nce you ha$e the ;4isual (tudio !ommand 8rompt /:%/; open, type in theollowing command and press enterIdasm.exe C:*+ourDirector$Pat*+ourAssem"$.exe

    This command should open the assemly and you will 7nd the maniest and thetypes &classes, structs etc..' in the assemly. At the ottom you can see the$ersion o the assemly.

    I' $ou %ant to sa,e te Intermediate Language to a text -e.(.(elect ile "enu rom the #L*A(" tool.).(elect *ump and you will see ;*ump ptions Window;.!lic6 < on ;*ump ptions Window;/.Now enter the 7le name o your choice. or this example let3s enter sampleand sa$e it to the != dri$e.

    0.Now na$igate to != dri$e in windows explorer and you should see (ample.il1.pen (ample.il with notepad and you should see assemly metadata and#Lntermediate Language'.

    I' $ou %ant to re"uid an Assem"$ 'rom te Same.i -e %e can use atoo ILASM.exe(.Type the ollowing command in ;4isual (tudio !ommand 8rompt; and pressenterILASM.exe C:*Same.i).Now na$igate to != dri$e in windows explorer and you should see (ample.exe

    2e use ILDASM 3Intermediate Language Disassem"er4 to ee! at teassem"$ mani'est and IL. +ou can aso use tis too to exort mani'estand IL to a text -e.

    2e use ILASM.exe 3Intermediate Language Assem"er4 to reconstructan assem"$ 'rom a text -e tat contains mani'est and IL.

    ASSEMBL+ IN .NET 56AME2768:

    The .NET assemly is the standard or components de$eloped with the"icrosot.NET. *ot NET assemlies may or may not e executale, i.e., theymight exist as the executale &.exe' 7le or dynamic lin6 lirary &*LL' 7le. Allthe .NET assemlies contain the de7nition o types, $ersioning inormation orthe type, meta2data, and maniest. The designers o .NET ha$e wor6ed a lot onthe component &assemly' resolution.

    There are two 6ind o assemlies in .NET> pri$ate

    shared

    What is GAC. How and when to install an assembly into GAC

  • 7/24/2019 C# Notes.docx

    3/82

    Abbreviated as GAC, the GlobalAssembly Cacheis a machine-wide store used to hold assembliesthat areintended to be shared by several applications on the machine. Each computerwhere the common languageruntime (C!" is installed has a global assemblycache.#he global assembly cache stores the assembliesspeci$ically designated to be shared by several applications on the computer.

    #he .%E#&ramewor' provides two tools $or wor'ing with the cache. ne is a Windows shell e)tension that

    allows you to wor' with the cache using a Graphical *ser +nter$ace (G*+". #he other is a command line tool,called the Global Assembly Cache tool (Gacutil.e)e", that is typically used in build and test scripts.

    What is DLL HELL in .NET:

    1.+ have applications, A and A installed on my computer.

    2.oth o$ these applications use shared assembly shared.dll

    3.%ow, + have a latest version o$ Application - A available on the internet.

    4.+ download the latest version o$ A and install it on my machine.

    5.#his new installation has over written /hared.dll, which is also used by Application - A.

    6.Application - A wor's $ine, but A $ails to wor', because the newly installed /hared.dll is notbac'ward compatible.

    /o, 0 HE is a problem where one application will install a new version o$ the shared componentthat is not bac'ward compatible with the version already on the machine, causing all the other e)istingapplications that rely on the shared component to brea'. With .%E# versioning we donot have 0

    HE problem any more.

    How is the DLL HELL problem solved in .NET

    Consider the example below:+ have applications, Application - A1and Application - A2which relies on the sharedassembly Accessibility.dll (ersion 2.!.!.!"as shown in the image below.

    2.%ow, + have a latest version o$ Application - A2available on the internet.3.+ download the latest version o$ A2and install it on my machine.

    4.#his new installation copies a newer version o$ Accessibility.dll into the GAC with version 3.!.!.!.5./o, in the GAC we now have 2 #ersions o$ Accessibility.dll.

    http://www.webopedia.com/TERM/A/assembly.htmlhttp://www.webopedia.com/TERM/C/computer.htmlhttp://www.webopedia.com/TERM/C/computer.htmlhttp://www.webopedia.com/TERM/C/CLR.htmlhttp://www.webopedia.com/TERM/C/CLR.htmlhttp://www.webopedia.com/TERM/C/cache.htmlhttp://www.webopedia.com/TERM/C/cache.htmlhttp://www.webopedia.com/TERM/C/cache.htmlhttp://www.webopedia.com/TERM/D/dot_NET.htmlhttp://www.webopedia.com/TERM/D/dot_NET.htmlhttp://www.webopedia.com/TERM/G/GUI.htmlhttp://www.webopedia.com/TERM/S/script.htmlhttp://www.webopedia.com/TERM/C/computer.htmlhttp://www.webopedia.com/TERM/C/CLR.htmlhttp://www.webopedia.com/TERM/C/cache.htmlhttp://www.webopedia.com/TERM/D/dot_NET.htmlhttp://www.webopedia.com/TERM/G/GUI.htmlhttp://www.webopedia.com/TERM/S/script.htmlhttp://www.webopedia.com/TERM/A/assembly.html
  • 7/24/2019 C# Notes.docx

    4/82

    6.Application - A1continues to use Accessibility.dll (#ersion 2.!.!.!"and Application - A2 %sesAccessibility.dll (#ersion 3.!.!.!"&./o, now the assemblies are able to reside side by side in the GAC. &or this reason dot netassemblies are also said to be supporting side by side exec%tion.

    C#

    'n C types are di#ided into 2 broad cate)ories.al%e *ypes - int, $loat, double, structs, enums etc+e$erence *ypes1 +nter$ace, Class, delegates, arrays etc

    ,y de$a%lt #al%e types are non n%llable. *o mae them n%llable %se inti 2 3 (i is non nullable, so 4i4 cannot be set to null, i 2 null will generate compiler error"int5 6 2 3 (6 is nullable int, so 62null is legal"

    /0 coalescin) operator:

    ro)ram witho%t %sin) /0 coalescin) operatorusing/ystem7class 8rogram9 static void:ain(" 9 intAvailable#ic'ets7 int5 #ic'etsn/ale 2 null7

    i$(#ic'etsn/ale 22 null" 9 Available#ic'ets 2 37 ; else 9 Available#ic'ets 2 (int"#ic'etsn/ale7 ;

    Console.Writeine(4Available #ic'ets293;4, Available#ic'ets"7 ;;

    *he abo#e pro)ram is re-written %sin) /0 coalescin) operatorusing/ystem7class 8rogram9 static void:ain(" 9 intAvailable#ic'ets7 int5 #ic'etsn/ale 2 null7

  • 7/24/2019 C# Notes.docx

    5/82

    ;;

    0atatype conversions

    'mplicit con#ersion is done by the compiler:1.When there is no loss o$ in$ormation i$ the conversion is done2.+$ there is no possibility o$ throwing e)ceptions during the conversion

    xample: Converting an intto a $loatwill not loose any data and no e)ception will bethrown, hence an implicit conversion can be done.

    Where as when converting a $loatto an int, we loose the $ractional part and also apossibility o$ over$low e)ception. Hence, in this case an e)plicit conversion is re=uired. &or

    e)plicit conversion we can use cast operator or the convert class in c>.

    'mplicit Con#ersion xampleusing/ystem7class 8rogram9 public static void:ain(" 9 int i 2 337

  • 7/24/2019 C# Notes.docx

    6/82

    Console.Writeine(i"7 ;;

    i$$erence between arse and *ryarse1.+$ the number is in a string $ormat you have options - 8arse(" and #ry8arse("2.8arse(" method throws an e)ception i$ it cannot parse the value, whereas #ry8arse("returns a bool indicating whether it succeeded or $ailed.3.*se 8arse(" i$ you are sure the value will be valid, otherwise use #ry8arse("

    A!!A/ +% C>

    An array is a collection o$ similar data types.

    using/ystem7class 8rogram9 public static void:ain(" 9

  • 7/24/2019 C# Notes.docx

    7/82

    isad#anta)es:Arrays cannot grow in siBe once initialiBed. Have to rely on integral indicesto store or retrieve items $rom the array.

    *7 ''/8 (9A 1"

    *7 7++''/8 ''/8 ; (9A 2"

  • 7/24/2019 C# Notes.docx

    8/82

    *7 7++''/8 ''/8 ; (9A 3"

  • 7/24/2019 C# Notes.docx

    9/82

    Po$morism:

    When a message can be processed in different ways is called polymorphism.

    Polymorphism means many forms.

    Polymorphism is one of the fndamental concepts of !!P.

  • 7/24/2019 C# Notes.docx

    10/82

    Polymorphism provides following features:

    "t allows yo to invo#e methods of derived class throgh base class reference

    dring rntime.

    "t has the ability for classes to provide different implementations of methods that

    are called throgh the same name.

    Polymorphism is of two types:

    . $ompile time polymorphism%!verloading

    . &ntime polymorphism%!verriding

    Compile *ime olymorphism

    $ompile time polymorphism is method and operators overloading. "t is also called early

    binding.

    "n method overloading method performs the different tas# at the different inpt

    parameters.

    +%ntime *ime olymorphism

    &ntime time polymorphism is done sing inheritance and virtal fnctions. 'ethod

    overriding is called rntime polymorphism. "t is also called late binding.

    When overridinga method( yo change the behavior of the method for the derived

    class. Overloadinga method simply involves having another method with the same

    prototype.

    Caution: Don)t confsed method overloading with method overriding( they are different(

    nrelated concepts. *t they sond similar.

    'ethod overloading has nothing to do with inheritance or virtal methods.

  • 7/24/2019 C# Notes.docx

    11/82

  • 7/24/2019 C# Notes.docx

    12/82

    4

    staticvoid'ain+string56 args,

    0

    Printob7 8 newPrint+,-

    ob7.display+19eorge1,-

    ob7.display+;( ?f,-

    $onsole.&eadLine+,-

    4

    4

    4

    Note: "n the code if yo observe display method is called two times. Display method will

    wor# according to the nmber of parameters and type of parameters.

    =hen and why to %se method o#erloadin)

    @se method overloading in sitation where yo want a class to be able to do something(

    bt there is more than one possibility for what information is spplied to the method that

    carries ot the tas#.

    2o shold consider overloading a method when yo for some reason need a cople of

    methods that ta#e different parameters( bt conceptally do the same thing.

    Proerties in C#:

    "n $A( properties are nothing bt natral eBtension of data fields. They

    are sally #nown as )smart fields) in $A commnity. We #now that data

    encapslation and hiding are the two fndamental characteristics of any

    ob7ect oriented programming langage."n $A( data encapslation is

    possible throgh either classes or strctres. *y sing varios access

    modifiers li#e private( pblic( protected( internal etc it is possible tocontrol the accessibility of the class members.

  • 7/24/2019 C# Notes.docx

    13/82

    @sally inside a class( we declare a data field as private and will provide a

    set of pblic ET and 9ET methods to access the data fields. This is a

    good programming practice( since the data fields are not directly

    accessible ot side the class. We mst se the set%get methods to access

    the data fields.

    singystem-

    class'y$lass0

    privateintB-

    pblicintC0

    get0

    retrnB-4

    set

    0B 8 vale-

    44

    4class'y$lient

    0

    pblicstaticvoid'ain+,0

    'y$lass mc 8 new'y$lass+,-mc.C 8 ?-

    intBal 8 mc.C-$onsole.WriteLine+Bal,-%%Displays ?

    4

    4

    &emember that a property shold have at least one accessor( either set or

    get. The set accessor has a free variable available in it called vale( which

    gets created atomatically by the compiler. We can)t declare any variable

    with the name vale inside the set accessor.

    We can do very complicated calclations inside the set or get accessor.

    Even they can throw eBceptions.

    ince normal data fields and properties are stored in the same memory

    space( in $A( it is not possible to declare a field and property with the

    same name.

    Static Properties

  • 7/24/2019 C# Notes.docx

    14/82

    $A also spports static properties( which belongs to the class rather than

    to the ob7ects of the class. Fll the rles applicable to a static member are

    applicable to static properties also.

    The following program shows a class with a static property.

    %%$A : static Property

    %%Fthor: ra7eshvsGmsn.com

    singystem-

    class'y$lass

    0

    privatestaticintB-

    pblicstaticintC

    0

    get

    0

    retrnB-

    4

    set

    0

    B 8 vale-

    4

    4

    4class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    'y$lass.C 8 ?-

    intBal 8 'y$lass.C-

    $onsole.WriteLine+Bal,-%%Displays ?

    4

    4

    &emember that set%get accessor of static property can access only other

    static members of the class. Flso static properties are invo#ing by sing

    the class name.

    Properties & Inheritance

    The properties of a *ase class can be inherited to a Derived class.

    %%$A : Property : "nheritance

    %%Fthor: ra7eshvsGmsn.com

  • 7/24/2019 C# Notes.docx

    15/82

    singystem-

    class*ase

    0

    pblicintC

    0get

    0

    $onsole.Write+1*ase 9ET1,-

    retrn?-

    4

    set

    0

    $onsole.Write+1*ase ET1,-

    4

    4

    4

    classDerived : *ase

    0

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    Derived d 8 newDerived+,-d.C 8 ?-

    $onsole.WriteLine+d.C,-%%Displays )*ase ET *ase 9ET ?)

    4

    4

    The above program is very straightforward. The inheritance of properties

    is 7st li#e inheritance any other member.

    Properties & Polymorphism

    F *ase class property can be polymorphicaly overridden in a Derived

    class. *t remember that the modifiers li#e virtal( override etc are sing

    at property level( not at accessor level.

    %%$A : Property : Polymorphism

    %%Fthor: ra7eshvsGmsn.com

    singystem-

    class*ase

    0pblicvirtalintC

  • 7/24/2019 C# Notes.docx

    16/82

    0

    get

    0

    $onsole.Write+1*ase 9ET1,-

    retrn?-4

    set

    0

    $onsole.Write+1*ase ET1,-

    4

    4

    4

    classDerived : *ase

    0

    pblicoverrideintC

    0

    get

    0

    $onsole.Write+1Derived 9ET1,-

    retrn?-

    4

    set

    0

    $onsole.Write+1Derived ET1,-4

    4

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    *ase b 8 newDerived+,-

    b.C 8 ?-

    $onsole.WriteLine+b.C,-%%Displays )Derived ET Derived 9ET ?)

    4

    4

    Abstract Properties

    F property inside a class can be declared as abstract by sing the

    #eyword abstract. &emember that an abstract property in a class carries

    no code at all. The get%set accessors are simply represented with a

    semicolon. "n the derived class we mst implement both set and getassessors.

  • 7/24/2019 C# Notes.docx

    17/82

    "f the abstract class contains only set accessor( we can implement only set

    in the derived class.

    The following program shows an abstract property in action.

    %%$A : Property : Fbstract

    %%Fthor: ra7eshvsGmsn.com

    singystem-

    abstractclassFbstract

    0

    pblicabstractintC

    0

    get-

    set-

    4

    4

    class$oncrete : Fbstract

    0

    pblicoverrideintC

    0

    get

    0

    $onsole.Write+1 9ET1,-

    retrn?-4

    set

    0

    $onsole.Write+1 ET1,-

    4

    4

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    $oncrete c 8 new$oncrete+,-

    c.C 8 ?-

    $onsole.WriteLine+c.C,-%%Displays )ET 9ET ?)

    4

    4

  • 7/24/2019 C# Notes.docx

    18/82

    Structures in C#:

    F strctre in $A is simply a composite data type consisting of a nmber

    elements of other types. F $A strctre is a vale type and the instances or

    ob7ects of a strctre are created in stac#. The strctre in $A can contain

    fields( methods( constants( constrctors( properties( indeBers( operators and

    even other strctre types.

    Structure eclaration & Ob!ect Creation

    The #eyword strct can be sed to declare a strctre. The general form of a

    strctre declaration in $A is as follows.

    modifiersI strctstrct/nameI

    0

    %%trctre members4

    Where the modifier can be private( pblic( internal or pblic. The strct is the

    reJired #eyword.

    Kor eBample

    strct'ytrct

    0

    pblicintB-

    pblicinty-

    4

    The ob7ects of a strct can be created by sing the new operator as

    follows.

    'ytrct ms 8 new'ytrct+,-

    The individal members of a strct can be accessed by sing the dot +.,

    operator as showing below.

    ms.B 8 ?-

    ms.y 8 ?-

    &emember that nli#e classes( the strct ob7ect can also be created withot

    sing the new operator.

    'ytrct ms-

  • 7/24/2019 C# Notes.docx

    19/82

    *t in this case all fields of the strct will remain nassigned and the ob7ect

    can)t be sed ntil all of the fields are initialiMed.

    Structs & "ields

    F strct in $A can contain fields. These fields can be declared as private(

    pblic( internal. &emember that inside a strct( we can only declare a field.

    We can)t initialiMe a field inside a strct. However we can se constrctor to

    initialiMe the strctre fields.

    The following is not a valid $A strct and the code will not compile( since the

    fields inside the strctre are trying to initialiMe.

    strct'ytrct

    0intB 8 ?-%% Error its not possible to initialiMe

    inty 8 ?-%% Error its not possible to initialiMe

    4

    F valid $A strctre is showing below.

    %% Fthor: ra7eshvsGmsn.com

    singystem-

    strct'ytrct

    0

    pblicintB-

    pblicinty-

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    'ytrct ms 8 new'ytrct+,-

    ms.B 8 ?-ms.y 8 ?-

    intsm 8 ms.B 3 ms.y-

    $onsole.WriteLine+1The sm is 0?41(sm,-

    4

    4

    However a strct can contain static fields( which can be initialiMed inside the

    strct. The following eBample shows the se of static fields inside a strct.

    %% Fthor: ra7eshvsGmsn.com

    singystem-

  • 7/24/2019 C# Notes.docx

    20/82

    strct'ytrct

    0

    pblicstaticintB 8 >-

    pblicstaticinty 8 >?-

    4class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    intsm 8 'ytrct.B 3 'ytrct.y-

    $onsole.WriteLine+1The sm is 0?41(sm,-

    4

    4

    &emember that static fields can)t be accessed by an instance of a strct. We

    can access them only by sing the strct names.

    Struct & #ethods

    F $A strct can also contain methods. The methods can be either static or

    nonstatic. *t static methods can access only other static members and

    they can)t invo#e by sing an ob7ect of the strctre. They can invo#e only

    by sing the strct name.

    Fn eBample is shown below.

    %% Fthor: ra7eshvsGmsn.com

    singystem-

    strct'ytrct

    0

    staticintB 8 >-

    staticinty 8 >?-

    pblicvoidetC2+inti( int7,

    0

    B 8 i-

    y 8 7-

    4

    pblicstaticvoidhowm+,

    0

    intsm 8 B 3 y-

    $onsole.WriteLine+1The sm is 0?41(sm,-

    4

    4

    class'y$lient

  • 7/24/2019 C# Notes.docx

    21/82

    0

    pblicstaticvoid'ain+,

    0

    'ytrct ms 8 new'ytrct+,-

    ms.etC2+??(??,-'ytrct.howm+,-

    4

    4

    The methods inside a strct can also be overloaded as li#e inside a class. Kor

    eBample

    %% Fthor:ra7eshvsGmsn.com

    singystem-

    strct'ytrct

    0

    staticintB 8 >-

    staticinty 8 >?-

    pblicvoidetC2+inti( int7,

    0

    B 8 i-

    y 8 7-

    4

    pblicvoidetC2+inti,0

    B 8 i-

    y 8 i-

    4

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    'ytrct ms 8 new'ytrct+,-

    'ytrct ms 8 new'ytrct+,-

    ms.etC2+??(??,-

    ms.etC2+>??,-

    4

    4

    Structs & Constructors

    F $A strct can declare constrctor( bt they mst ta#e parameters. Fdefalt constrctor +constrctor withot any parameters, are always provided

  • 7/24/2019 C# Notes.docx

    22/82

    to initialiMe the strct fields to their defalt vales. The parameteriMed

    constrctors inside a strct can also be overloaded.

    %% Fthor: ra7eshvsGmsn.com

    singystem-strct'ytrct

    0

    intB -

    inty -

    0 B 8 i- y 8 7-4

    pblic'ytrct+inti,

    0 B 8 y 8 i- 4

    pblicvoidhowC2+,

    0 $onsole.WriteLine+1The field vales are 0?4 O 041(B(y,- 4

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    'ytrct ms 8 new'ytrct+?(?,-

    'ytrct ms 8 new'ytrct+?,-

    ms.howC2+,-

    ms.howC2+,-

    44

    The )this) operator can also be sed in constrctors and parameteriMed

    constrctors can be chained inside a $A constrctor. Fn eBample is given

    below.

    %% Fthor: ra7eshvsGmsn.com

    singystem-

    strct'ytrct

    0

    intB -

    inty -

    pblic'ytrct+inti( int7,:this+i37,

    0 4

    pblic'ytrct+inti,

    0 B 8 y 8 i- 4

    pblicvoidhowC2+,

    0 $onsole.WriteLine+1The field vales are 0?4 O 041(B(y,- 4

    4class'y$lient

  • 7/24/2019 C# Notes.docx

    23/82

    0

    pblicstaticvoid'ain+,

    0

    'ytrct ms 8 new'ytrct+?(?,-

    ms.howC2+,-4

    4

    Kinally remember that $A strct do not spport destrctors.

    Structs & Properties

    The properties can be declared inside a strct as shown below.

    %%$A: Property%% Fthor: ra7eshvsGmsn.com

    sing ystem-

    class'ytrct

    privateintB-

    pblicintC

    0

    get

    0

    retrnB-

    4

    set

    0

    B 8 vale-

    4

    4

    4

    class'y$lient

    pblicstaticvoid'ain+,

    0

    'ytrct ms 8 new'ytrct+,-

    ms.C 8 ?-

    intBal 8 ms.C-

    $onsole.WriteLine+Bal,-%%Displays ?

    4

    4

    Structs & Inde$ers

  • 7/24/2019 C# Notes.docx

    24/82

    The indeBers can also be sed with a $A strct. Fn eBample is shown

    below.

    %% Fthor: ra7eshvsGmsn.com

    singystem-singystem.$ollections-

    strct'ytrct

    0

    pblicstring56data -

    pblicstringthis5intindeB6

    0

    get

    0

    retrndata5indeB6-

    4

    set

    0

    data5indeB6 8 vale-

    4

    4

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,0

    'ytrct ms 8 new'ytrct+,-

    ms.data 8 newstring5>6-

    ms5?6 8 1&a7esh1-

    ms56 8 1F=1-

    ms56 8 1nehadara1-

    ms56 8 1"rla1-

    ms5;6 8 1'mbai1-

    $onsole.WriteLine+10?4(04(04(04(0;41(ms5?6(ms56(ms56(ms56(ms5;6,-

    4

    4

    Structs & Operator Overloading

    The operators can be overloaded inside a $A strctre also. The same rles

    applicable with respect to a $A class is also applicable here. *oth nary and

    binary operators can be overloaded.

    %% Fthor: ra7eshvsGmsn.comsingystem-

  • 7/24/2019 C# Notes.docx

    25/82

  • 7/24/2019 C# Notes.docx

    26/82

    ince inheritance is not spported for strcts( the declared accessibility of a

    strct member can)t be protected or protected internal. ince all strct types

    are implicitly inherit from ob7ect class( it is possible to override the methods

    of the ob7ect class inside a strct by sing the #eyword override. &emember

    that this is special case in $A strcts.

    Structs & Interfaces

    st li#e classes( a $A strct can also implement from an interface. Kor

    eBample

    %% Fthor:ra7eshvsGmsn.com

    singystem-

    interface""nterface

    0void'ethod+,-

    4

    strct$ompleB : ""nterface

    0

    pblicvoid'ethod+,

    0

    $onsole.WriteLine+1trct 'ethod1,-

    4

    4

    class'y$lient

    0

    pblicstaticvoid'ain+,

    0

    $ompleB c 8 new$ompleB+,-

    c.'ethod+,-

    4

    4

    Structs & Classes

    The strcts in $A seems to similar to classes. *t they are two entirely

    different aspects of the langage. The classes are reference types while a

    strct is a vale type in $A. The ob7ects of class types are always created on

    heal while the ob7ects of strct types are always created on the stac#. *t

    $A strcts are sefl for small data strctres that have vale semantics.

    $ompleB nmbers( points in a coordinate systems etc are good eBamples for

    strct types.

  • 7/24/2019 C# Notes.docx

    27/82

    Di9erence "et%een A"straction and Encasuation

    Astraction is ;To represent the essential eature without representing theac6 ground details.;

    Astraction lets you ocus on what the o-ect does instead o how it doesit.

    0eal world Example o Astraction= 2(uppose you ha$e an o-ect "oile 8hone.

    (uppose you ha$e ? moile phones as ollowing=2

    No6ia %@:: &eatures=2 !alling, ("('No6ia /:: &eatures=2 !alling, ("(, " 0adio, "8?, !amera')lac6 )erry &eatures=2!alling, ("(, " 0adio, "8?, !amera, 4ideo 0ecording,0eading E2mails'

    Astract inormation &Necessary and !ommon #normation' or the o-ect ;"oile8hone; is ma6e a call to any numer and can send ("(.;

    so that, or moile phone o-ect you will ha$e astract class li6e ollowing=2

    astract class "oile8hone B pulic $oid !alling&'> pulic $oid (end("(&'>

    C

    pulic class No6ia%@:: = "oile8hone B

    C

    pulic class No6ia/:: = "oile8hone B pulic $oid "0adio&'> pulic $oid "8?&'> pulic $oid !amera&'>

    C

    pulic class )lac6)erry = "oile8hone B pulic $oid "0adio&'> pulic $oid "8?&'> pulic $oid !amera&'> pulic $oid 0ecording&'> pulic $oid 0eadAnd(endEmails&'>

    C

  • 7/24/2019 C# Notes.docx

    28/82

    #nteraces, astract classes or inheritance and polymorphism are tools topro$ide astraction in cD.

    Encasuation:Wrapping up data memer and method together into a single unit &i.e.!lass' is called Encapsulation.

    Encapsulation is li6e your ag in which you can 6eep your pen, oo6 etc. #tmeans this is the property o encapsulating memers and unctions.

    class )ag

    B oo6>

    pen> 0ead)oo6&'>

    WriteText&'> C

    2!lasses, properties and access modi7ers are tools to pro$ideencapsulation in cD.

    Ineritance:

    When a class acuire the property o another class is 6nown as inheritance.

    #nheritance is process o o-ect reusaility.or example, A !hild acuire property o 8arents.

    pulic class 8arent!lass B

    pulic 8arent!lass&' B

    !onsole.WriteLine&;8arent !onstructor.;'> C

    pulic $oid print&'

    B !onsole.WriteLine&;#3m a 8arent !lass.;'>

    C C

    pulic class !hild!lass = 8arent!lass

    B pulic !hild!lass&'

    B

    !onsole.WriteLine&;!hild !onstructor.;'>

    C

    pulic static $oid "ain&'

  • 7/24/2019 C# Notes.docx

    29/82

    B

    !hild!lass child F new !hild!lass&'>

    child.print&'>

    C

    C

    utput=

    8arent !onstructor.

    !hild !onstructor.

    #3m a 8arent !lass.

    Po$morism:

    8olymorphism means one name many orms.ne unction eha$es diferent orms.#n other words, ;"any orms o a single o-ect is called 8olymorphism.;

    0eal World Example o 8olymorphism=Example2%=A Teacher eha$es to student.A Teacher eha$es to hisGher seniors.Here teacher is an o-ect ut attitude is diferent in diferent situation.Example2/=8erson eha$es (N in house at the same time that person eha$es E"8LIEE

    in oJce.Example2?=Iour moile phone, one name ut many orms

    As phone As camera As mp? player As radio

    Constructors:

    #n simple terms, !onstructor is a special 6ind o method with class name as

    method name and gets executed when its &class' o-ect is created.!onstructors can e classi7ed into K types

    %. *eault !onstructor

    /. 8arameteried !onstructor

    ?. !opy !onstructor

    @. (tatic !onstructor

    K. 8ri$ate !onstructor

    *eault !onstructor = A constructor without any parameters is called as deaultconstructor. *rawac6 o deault constructor is e$ery instance o the class will e

    initialied to same $alues and it is not possile to initialie each instance o theclass to diferent $alues.

  • 7/24/2019 C# Notes.docx

    30/82

    8arameteried !onstructor = A constructor with at least one parameter is called

    as parameteried constructor. Ad$antage o parameteried constructor is you

    can initialie each instance o the class to diferent $alues.

    !opy !onstructor = A parameteried constructor that contains a parameter osame class type is called as copy constructor. "ain purpose o copy constructor

    is to initialie new instance to the $alues o an existing instance.

    In simple words a copy constructor means a constructor which copies data of one object into

    another object.

    class employee B pri$ate string name>

    pri$ate int age> pulic employee&string name, int age' GG #nstance constructor. B this.name F name> this.age F age> C pulic employee&employee emp' GG declaring !opy constructor. B name F emp.name> age F emp.age> C

    pulic string *etails GG Met deatils o employee B get B return ; The age o ; name ; is ; age.To(tring&'> C C C class empdetail B static $oid "ain&'

    B employee emp% F new employee&;4ithal;, /?'> GG !reate a newemployee o-ect. employee emp/ F new employee&emp%'> GG here is emp% details iscopied to emp/. !onsole.WriteLine&emp/.*etails'> !onsole.0eadLine&'> C CC

    (tatic !onstructor = Iou can create a constructor as static and when a

    constructor is created as static, it will e in$o6ed only once or any numer oinstances o the class and it is during the creation o 7rst instance o the class or

  • 7/24/2019 C# Notes.docx

    31/82

    the 7rst reerence to a static memer in the class. (tatic constructor is used toinitialie static 7elds o the class and to write the code that needs to e executedonly once.

    namespace 8rogram!all

    B class Test? B pulic Test?&' B !onsole.WriteLine&;#nstance !onstructor;'> C static Test?&' B !onsole.WriteLine&;(tatic !onstructor;'> C C

    class (tatic!onstructor B static $oid "ain&' B Test? T% F new Test?&'> GG )oth the constructors are in$o6ed Test? T/ F new Test?&'> GG When this o-ect is created only instanceconstructor is in$o6ed. !onsole.0ead&'> C CCutput 2

    (tatic !onstructor#nstance !onstructor#nstance !onstructor

    8ri$ate !onstructor = Iou can also create a constructor as pri$ate. When a classcontains at least one pri$ate constructor, then it is not possile to create aninstance or the class. 8ri$ate constructor is used to restrict the class rom einginstantiated when it contains e$ery memer as static.

    (ome uniue points related to constructors are as ollows

    A class can ha$e any numer o constructors. A constructor doesnOt ha$e any return type e$en $oid.

    A static constructor can not e a parameteried constructor.

    Within a class you can create only one static constructor.

    Note

    P A static constructor should not e declared with any access modi7er.

    P A static constructor does not accept parameters

    P A static constructor is called automatically.

    P There is no way to call a static constructor directly.

    P !anOt stop the execution o (tatic constructor

    Di9erence "et%een A"stract Cass and Inter'ace:What is an Astract !lassQ

  • 7/24/2019 C# Notes.docx

    32/82

    An astract class is a special 6ind o class that cannot e instantiated. (o the

    uestion is why we need a class that cannot e instantiatedQ An astract class is

    only to e su2classed &inherited rom'. #n other words, it only allows other

    classes to inherit rom it ut cannot e instantiated. The ad$antage is that it

    enorces certain hierarchies or all the suclasses. #n simple words, it is a 6ind o

    contract that orces all the suclasses to carry on the same hierarchies orstandards. The purpose o an astract class is to pro$ide a ase class de7nition

    or how a set o deri$ed classes will wor6 and then allow the programmers to 7ll

    the implementation in the deri$ed classes.

    What is an #nterace

    An interace is not a class. #t is an entity that is de7ned y the word #nterace. An

    interace has no implementation> it only has the signature or in other words, -ust

    the de7nition o the methods without the ody. As one o the similarities to

    Astract class, it is a contract that is used to de7ne hierarchies or all suclasses

    or it de7nes speci7c set o methods and their arguments. The main diference

    etween them is that a class can implement more than one interace ut can

    only inherit rom one astract class. (ince !D doesn3t support multiple

    inheritance, interaces are used to implement multiple inheritance.

    2at is an A"stract Metod

    Fn Fbstract method is a method withot a body. The implementation of an

    abstract method is done by a derived class. When the derived class inherits the

    abstract method from the abstract class( it mst override the abstract method.

    This reJirment is enforced at compile time and is also called dynamicpolymorphism.

    astractclasstest% B pulicintadd&inti, int-' B returni->

    C pulicastractintmul&inti, int-'> C

    classtest/=test% B pulico$errideintmul&inti, int-' B returniR-> C C classtest?=test%

    B pulico$errideintmul&inti, int-' B returni2->

    C C

  • 7/24/2019 C# Notes.docx

    33/82

    classtest@=test/B

    pulico$errideintmul&inti, int-' B returni->

    C C classmyclassB pulicstatic$oidmain &stringS args' B test/oF newtest@&'> inta F o.mul&/,@'> test%o%F newtest/&'> int F o%.mul&@,/'> test%o/F newtest?&'> intc F o/.mul&@,/'>

    !onsole.Write&;B:C,B%C,B/C;,a,,c'> !onsole.0eadLine &'> CC

    Inter'aces:

    An interace loo6s li6e a class, ut has no implementation. The only thing it contains aredeclarations o e$ents, indexers, methods andGor properties. The reason interaces onlypro$ide declarations is ecause they are inherited y structs and classes, that mustpro$ide an implementation or each interace memer declared.

    (o, what are interaces good or i they don3t implement unctionalityQ They3re great orputting together plug2n2play li6e architectures where components can e interchanged atwill. (ince all interchangeale components implement the same interace, they can eused without any extra programming. The interace orces each component to exposespeci7c pulic memers that will e used in a certain way.

    )ecause interaces must e implemented y deri$ed structs and classes, they de7ne acontract.

    interace#"y#nterace

    B

    $oid"ethodTo#mplement&'>GGAstract "ethod signature.

    C

    class#nterace#mplementer = #"y#nterace

    B

    static $oid"ain&'

    B

    #nterace#mplementer o- F new#nterace#mplementer&'>

    o-."ethodTo#mplement&'>

    C

    pulic$oid"ethodTo#mplement&'

  • 7/24/2019 C# Notes.docx

    34/82

    B

    GGAstract "ethod #mplementation

    C

    C

    7DDE;EN.cs

    using(ystem>using(ystem.!ollections.Meneric>using(ystem.Lin>using(ystem.Text>

    namespace#nterace*emoB interace#ne

    B $oidNE&'>GG8ure Astract "ethod (ignature C interace#Two B $oidTW&'> C interace#Three=#ne B $oidTH0EE&'> C interace#our B $oidU0&'> C interace#i$e=#Three B $oid#4E&'> C interace#E4EN=#Two,#our B

    C

    class**E4EN=#E4EN,#i$eGG"ust #mplement all the astract method, in*eri$ed class. B pulic$oidNE&'GG#mplementation o Astract "ethod. B !onsole.WriteLine&;This is NE;'> C pulic$oidTW&' B

    !onsole.WriteLine&;This is TW;'> C

  • 7/24/2019 C# Notes.docx

    35/82

    pulic$oidTH0EE&' B !onsole.WriteLine&;This is THE0E;'> C pulic$oidU0&'

    B !onsole.WriteLine&;This is U0;'> C pulic$oid#4E&' B !onsole.WriteLine&;This is #4E;'> C

    CC

    Program.cs

    using(ystem>using(ystem.!ollections.Meneric>using(ystem.Lin>using(ystem.Text>

    namespace#nterace*emoB class8rogram B

    static$oid"ain&stringS args' B !onsole.WriteLine&;This is **;'> #i$eo-% F new**E4EN&'> o-%.NE&'> o-%.TH0EE&'> o-%.#4E&'>

    !onsole.WriteLine&;nnThis is E4EN;'> #E4ENo-/ F new**E4EN&'> o-/.TW&'> o-/.U0&'>

    !onsole.0eadLine&'> C CC

    The ollowing is the output=

  • 7/24/2019 C# Notes.docx

    36/82

    Imicit & Exicit Inter'aces:

    Puroses o' Inter'aces

    . !reate loosely coupled sotware.

    . (upport design y contract &an implementer must pro$ide the entire interace'.

    @. Allow or pluggale sotware.

    . Allow o-ects to interact easily.

    ?. Hide implementation details o classes rom each other.

    I. acilitate reuse o sotware.

    Exame (

    interace#interaceV%B

    C

    class!lass%= #interaceV%B pulic$oid*isplay&' B

    !onsole.WriteLine&;!lass% *isplay "ethod.;'> CC

    class8rogramB static$oid"ain&stringS args' B !lass%o-!lass% F new!lass%&'> o-!lass%.*isplay&'> C

    C

  • 7/24/2019 C# Notes.docx

    37/82

    utput= !lass% *isplay "ethod

    Exame )

    The ollowing is an example o #mplicit and Explicit interace implementation=

    interace#interaceV%B $oidinterace%Vmethod&'>C

    class!lass%= #interaceV%B pulic$oid*isplay&' B

    !onsole.WriteLine&;!lass% *isplay "ethod.;'> C

    GG#mplicit interace implementation

    pulic$oidinterace%Vmethod&' B !onsole.WriteLine&;#interaceV% "ethod.;'> C

    GGExplicit interace implementation

    $oid#interaceV%.interace%Vmethod&' B !onsole.WriteLine&;#interaceV% "ethod.;'>

    CC

    class8rogramB static$oid"ain&stringS args' B !lass%o-!lass% F new!lass%&'> o-!lass%.*isplay&'> C

    C

    utput= !lass% *isplay "ethod.

    Exame

    The ollowing is an example o how to call an #mplicit interace method=

    interace#interaceV%B $oidinterace%Vmethod&'>C

    class!lass%= #interaceV%

  • 7/24/2019 C# Notes.docx

    38/82

    B pulic$oid*isplay&' B !onsole.WriteLine&;!lass% *isplay "ethod.;'> C

    GG#mplicit interace implementation pulic$oidinterace%Vmethod&' B !onsole.WriteLine&;#interaceV% "ethod #mplicit interace implementation.;'> C

    GGExplicit interace implementation

    $oid#interaceV%.interace%Vmethod&' B !onsole.WriteLine&;#interaceV% "ethod Explicit interace implementation.;'> CC

    class8rogramB static$oid"ain&stringS args' B !lass%o-!lass% F new!lass%&'> o-!lass%.*isplay&'>

    GG!all #mplicit interace method

    o-!lass%.interace%Vmethod&'>

    !onsole.0eadLine&'>

    C

    C

    utput= !lass% *isplay "ethod.

    #interaceV% "ethod #mplicit interace implementation.

    Note:

    #n the picture ao$e, when you type o-!lass%., then only interace%Vmethod will e

  • 7/24/2019 C# Notes.docx

    39/82

    shown and #interaceV%.interace%Vmethod is not ound.

    (o you can3t call explicit interace rom class o-ect. &i.e o-!lass%'

    Exame /

    The ollowing is an example o how to call an explicit interace method.

    interace#interaceV%B $oidinterace%Vmethod&'>C

    class!lass%= #interaceV%B pulic$oid*isplay&' B !onsole.WriteLine&;!lass% *isplay "ethod.;'>

    C

    GG#mplicit interace implementation pulic$oidinterace%Vmethod&' B !onsole.WriteLine&;#interaceV% "ethod #mplicit interace implementation.;'> C

    GGExplicit interace implementation

    $oid#interaceV%.interace%Vmethod&' B !onsole.WriteLine&;#interaceV% "ethod Explicit interace implementation.;'> CC

    class8rogramB static$oid"ain&stringS args' B !lass%o-!lass% F new!lass%&'> o-!lass%.*isplay&'>

    GG!all #mplicit interace method

    o-!lass%.interace%Vmethod&'>

    GG!all Explicit interace method #interaceV%o-V% F new!lass%&'> o-V%.interace%Vmethod&'>

    !onsole.0eadLine&'>

    C

    C

    utput= !lass% *isplay "ethod.

    #interaceV% "ethod #mplicit interace implementation.

    #interaceV% "ethod Explicit interace implementation.

  • 7/24/2019 C# Notes.docx

    40/82

    Deegates:

    There might be sitation in which yo want to pass methods arond to other methods.

    Kor this prpose we create delegate.

    F delegate is a class that encapslates a method signatre. Flthogh it can be sed in

    any conteBt( it often serves as the basis for the eventhandling model in $A bt can be

    sed in a conteBt removed from event handling +e.g. passing a method to a method

    throgh a delegate parameter,.

    A elegate %sage $ample

    namespace'yKirstDelegate

    0

    %%This delegate can point to any method(

    %%ta#ing two integers and retrning an

    %%integer.

    pblicdelegateint'yDelegate+intB( inty,-

    %%This class contains methods that 'yDelegate will point to.

    pblicclass'y$lass

    0

    pblicstaticintFdd+intB( inty,

    0

    retrnB 3 y-

    4

    pblicstaticint'ltiply+intB( inty,

    0

    retrnB Q y-

    4

    4

    classProgram

    0

    staticvoid'ain+string56 args, 0

    %%$reate an "nstance of 'yDelegate

    %%that points to 'y$lass.Fdd+,.

    'yDelegatedel 8 new'yDelegate+'y$lass.Fdd,-

    %%"nvo#e Fdd+, method sing the delegate.

    intadd&eslt 8 del+>( >,-

    $onsole.WriteLine+1> 3 > 8 0?4Rn1( add&eslt,-

    %%$reate an "nstance of 'yDelegate

    %%that points to 'y$lass.'ltiply+,.

    'yDelegatedel 8 new'yDelegate+'y$lass.'ltiply,-

    %%"nvo#e 'ltiply+, method sing the delegate.

  • 7/24/2019 C# Notes.docx

    41/82

    intmltiply&eslt 8 del+>( >,-

    $onsole.WriteLine+1> C > 8 0?41( mltiply&eslt,-

    $onsole.&eadLine+,-

    4

    44

    elegate ability to #ulticast

    Delegate)s ability to mlticast means that a delegate ob7ect can maintain

    a list of methods to call( rather than a single method

    if yo want to add a method to the invocation list of a delegate ob7ect (

    yo simply ma#e se of the overloaded 38 operator( and if yo want to

    remove a method from the invocation list yo ma#e se of the overloaded

    operator 8 .

    Note:The'lticast delegate here contain methods that retrn void( if

    yo want to create a mlticast delegate with retrn type yo will get the

    retrn type of the last method in the invocation list.

    A #ulticast elegate $ample

    namespace'y'lticastDelegate

    0 %%this delegate will be sed to call more than one

    %%method at once

    pblicdelegatevoid'lticastDelegate+intB( inty,-

    %%This class contains methods that 'yDelegate will point to.

    pblicclass'y$lass

    0

    pblicstaticvoidFdd+intB( inty,

    0

    $onsole.WriteLine+12o are in Fdd+, 'ethod1,-

    $onsole.WriteLine+10?4 3 04 8 04Rn1( B( y( B 3 y,-

    4

    pblicstaticvoid'ltiply+intB( inty,

    0

    $onsole.WriteLine+12o are in 'ltiply+, 'ethod1,-

    $onsole.WriteLine+10?4 C 04 8 041( B( y( B Q y,-

    4

    4

    classProgram

    0

    staticvoid'ain+string56 args,

  • 7/24/2019 C# Notes.docx

    42/82

    0

    %%$reate an "nstance of 'lticastDelegate

    %%that points to 'y$lass.Fdd+,.

    'lticastDelegatedel 8 new'lticastDelegate+'y$lass.Fdd,-

    %%sing the same instance of 'lticastDelegate %%to call 'y$lass.'ltibly+, by adding it to it)s

    %%invocation list.

    del 38 new'lticastDelegate+'y$lass.'ltiply,-

    %%"nvo#e Fdd+, and 'ltiply+, methods sing the delegate.

    %%Note that these methods mst have a void retrn vle

    $onsole.WriteLine+1QQQQcalling Fdd+, and 'ltibly+, 'ethods.QQQQRnRn1,-

    del+>( >,-

    %%removing the Fdd+, method from the invocation list

    del 8 new'lticastDelegate+'y$lass.Fdd,-

    $onsole.WriteLine+1RnRnQQQQFdd+, 'ethod removed.QQQQRnRn1,-

    %%this will invo#e the 'ltibly+, method only.

    del+>( >,-

    4

    4

    4

    E;ENTS:

    Windows based applications are message based. Fpplication is commnicating withwindows and windows are commnicating with application by sing predefined

    messages. .Net wraps p the messages with )'N(S). Fnd .Net reacting a particlarmessage by handling events. Events are the message sent by an ob7ect to indicate the

    occrrence of an event. Event can also be defined as a member that enables an ob7ectto provide notification. Events provide a powerfl means of interprocesscommnication. Events are sed for commnication between !b7ects. $ommnicationbetween !b7ects is done by events.

    Delegates are sed as the means of wiring p the event when the message is receivedby the application.

  • 7/24/2019 C# Notes.docx

    43/82

    vent *eceiver

    The event receiver may be

    1. Fn application

    2. Fn !b7ect

    3. F component

    Event receiver gets modified when something happens.

    vent Sender

    The Event sender may be

    1. Fn assembly in an application

    2. Fn ob7ect

    3. ystem events li#e 'ose event or #eyboard entry.

    Event sender)s 7ob is to raise the Event. Event sender doesn)t #now anything abot(

    whom and what the receiver is. To handle the event( there wold be some methodinside event receiver. This Event handler method will get eBected each time whenevent is registered to be raised.

    Here DELEGATE comes into action, because Sender has no idea who thereceiver will be.

    The P!"ESS o# hoo$in% u& the event handler is $nown as '((NG )P an

    Event.

    F simple eBample of wiring p is C+IC, 'N(.

    (he vent-andler elegate

    This Delegate is defined in .Net framewor#. "t is defined in ystem namespace. Fll of the

    events that are defined in .Net framewor# will se it.

  • 7/24/2019 C# Notes.docx

    44/82

    1. EventHandler cannot retrn any vale( so it shold retrn oid.

    2. Parameters are !b7ect and EventFrgs

    3. The first parameter is an !b7ect that raises the Event.

    4. The econd parameter is EventFrgs. This contains information abot the Event.

    $ample:

    Private void *tton/$lic#+!b7ect sender( EventFrgs e,04

    Here first parameter is a *tton- this cold be any btton if there are mltiple bttonson form.

    The econd parameter is EventFrags. This mainly contains the property for which *ttonis sed.

    $ample .:

    singystem-singystem.$ollections.9eneric-singystem.$omponent'odel-singystem.Data-singystem.Drawing-

    singystem.LinJ-

    singystem.TeBt-singystem.Windows.Korms-

    namespaceEventEBample

    0 pblicpartialclassKorm: Korm 0 pblicKorm+, 0 "nitialiMe$omponent+,- %% Fdding EventHandler to $lic# event of *ttons btn.$lic# 38newEventHandler+*tton/$lic#,-

    btn.$lic# 38newEventHandler+*tton/$lic#,-

    4

    %% *tton $lic# 'ethod ( here signatre of this is same as of Eventhandler

    privatevoid*tton/$lic#+!b7ectsender( EventFrgse, 0 stringstr- if+sender 88 btn, 0 str 8 btn.TeBt-

    'essage*oB.how+str31 $lic#ed 1,- 4

    if+sender 88 btn,

    0 str 8 btn.TeBt-

  • 7/24/2019 C# Notes.docx

    45/82

    'essage*oB.how+str3 1 $lic#ed 1,- 4 4

    44

    CANDLIN?:

    $reating @serDefined EBceptions

    2o can also define yor own eBception. @serdefined eBception classes

    are derived from the $ceptionclass. The following eBample

    demonstrates this:

    using(ystem>

    namespaceUser*e7nedException

    B

    classTestTemperature

    B

    static$oid"ain&stringSargs'

    B

    Temperaturetemp FnewTemperature&'>

    try

    B

    temp.showTemp&'>

    C

    catch&Temp#seroExceptione'

    B

    !onsole.WriteLine&;Temp#seroException= B:C;,e."essage'>

    C

    !onsole.0ead

  • 7/24/2019 C# Notes.docx

    46/82

    pulicTemp#seroException&stringmessage'=ase&message'

    B

    C

    C

    pulicclassTemperature

    B

    inttemperature F:>

    pulic$oidshowTemp&'

    B

    i&temperature FF:'

    B

    throw&newTemp#seroException&;ero Temperature ound;''>

    C

    else

    B

    !onsole.WriteLine&;Temperature= B:C;,temperature'>

    C

    C

    C

    When the above code is compiled and eBected( it prodces the following

    reslt:

    Temp#seroException= ero Temperature ound

    EN

  • 7/24/2019 C# Notes.docx

    47/82

    enm is sed to create nmeric constants in .NET framewor#. Fll member of enm are of

    enm type. There mst be a nmeric vale for each enm type.

    The defalt nderlying type of the enmeration elements is int. *y defalt( the first

    enmerator has the vale ?( and the vale of each sccessive enmerator is increasedby .

    enumDow{Sat, Sun, Mon, Tue, Wed, Thu, Fri};

    Pro%ram to demonstrate how to create and )se an Enum:

    usingSystem;

    namespaceexample_enum

    {

    classrogram

    {

    pu!licenumDayo"Wee#

    {

    Sunday $ %, Monday, Tuesday, Wednesday, Thursday, Friday,

    Saturday

    }

    static&oidMain'string() args* {

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Sunday,Dayo"Wee#Sunday*;

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Monday,Dayo"Wee#Monday*;

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Tuesday,Dayo"Wee#Tuesday*;

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Wednesday,Dayo"Wee#Wednesday*;

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Thursday,Dayo"Wee#Thursday*;

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Friday,Dayo"Wee#Friday*;

    +onsoleWrite-ine'.Day o" wee# {/} {%}.,

    'int*Dayo"Wee#Saturday,Dayo"Wee#Saturday*;

    +onsole0ead-ine'*;

    }

    }

    }

  • 7/24/2019 C# Notes.docx

    48/82

    Some points about enum:

    enms are enmerated data type in cA.

    enms are not for endser( they are meant for developers.

    enms are strongly typed constant. They are strongly typed( i.e. an enm of one

    type may not be implicitly assigned to an enm of another type even thogh the

    nderlying vale of their members are the same.

    Enmerations +enms, ma#e yor code mch more readable and nderstandable.

    enm vales are fiBed. enm can be displayed as a string and processed as an

    integer.

    The defalt type is int( and the approved types are byte( sbyte( short( short(

    int( long( and long.

    Every enm type atomatically derives from ystem.Enm and ths we can se

    ystem.Enm methods on enms.

    Enms are vale types and are created on the stac# and not on the heap.

    1ou give two same values in enum type0

    2es we can have same vale in enm type. EBample when we want to set priority options

    li#e

    Normal ?

    EBcellent

    Defalt ?

    9ood

    ACCESS M7DI5IE6S:

    =hy to %se access modi$iers

    Fccess modifiers are an integral part of ob7ectoriented programming. They spport the

    concept of encapslation( which promotes the idea of hiding fnctionality. Fccess

    modifiers allow yo to define who does or doesn)t have access to certain featres.

    In C2 there are 3 different types of Access #odifiers4

  • 7/24/2019 C# Notes.docx

    49/82

    #odifier escription

    pblic There are no restrictionson accessing pblic

    members.

    private Fccess is limited to within

    the class definition. This is

    the defalt access modifier

    type if none is formally

    specified

    protected Fccess is limited to within

    the class definition and

    any class that inherits

    from the class

    internal Fccess is limited

    eBclsively to classesdefined within the crrent

    pro7ect assembly

    protected

    internal

    Fccess is limited to the

    crrent assembly and

    types derived from the

    containing class. Fll

    members in crrent

    pro7ect and all members in

    derived class can access

    the variables.

    ATT6IB

  • 7/24/2019 C# Notes.docx

    50/82

    method. &or e)ample .%E# $ramewor' provides the system.obsoleteAttribute

    attribute which can be used to mar' a method as $ollowswe use D brac'ets to attach

    attributes to code elementsD

    /ystem.bsoleteAttribute("Dvoid&un9;

    #he &un method is mar'ed with the system.bsoleteAttribute attribute in$ormation is

    inserted in the assembly during compilation. #his in$ormation then can be used by

    the c> compiler. When it encounters a call to method, it can then emit a warning

    indicating it is better to avoid call to an obsolete method, which ris's o$ going away in

    $uture versions. Without an attribute, you would be $orced to properly document the

    $act that &un(" method is now obsolete the wea'ness o$ this approach is that you will

    have no guarantee that your clients will read the documentation and be aware o$ the

    $act that method is now obsolete.

    6E5LECTI7N:

    Introduction

    "n $A( &eflection is a process by which we can get the detailed information from

    assembly( li#e abot method( constrctor( attribte( property( modle( global class(

    parameters( and many more at rn time. &eflection can modify strctre and behavior of

    a compter program.

    /hat is *eflection in C2

    1&eflection is a mechanism by which we can get metadata information from assembly at

    rn time.1

    /hen use *eflection

    "f we want to #now assembly information at rn time (then we se reflection. &eflection

    are sed for data binding in .NET Kramewor#. "t is also sed for testing in .NET

    Kramewor#.

    -ow to use

    There are ystem.&eflection is the namespace for the reflection. ystem.&eflection

    namespace defines the assembly modle( 'ember"nfo( Property"nfo( 'ethod"nfo(

    $onstrctor"nfo( Kield"nfo( Event"nfo etc.

    The ystem.Type is the base class for reflection. ystem.Type find the type name(

    namespace( modle type etc. ystem.Type is also an abstract class .

    singystem-

  • 7/24/2019 C# Notes.docx

    51/82

    singystem.$ollections.9eneric-

    singystem.$omponent'odel-

    singystem.Data-

    singystem.Drawing-

    singystem.LinJ-

    singystem.TeBt-singystem.Windows.Korms-

    singystem.&eflection-

    namespacereflection

    0

    pblicpartialclassKorm: Korm

    0

    pblicKorm+,

    0 "nitialiMe$omponent+,-

    4

    privatevoidKorm/Load+ob7ectsender( EventFrgse,

    0 intn 8 ;>-

    %%string n 8 1vineet1-

    ystem.Typet 8 n.9etType+,-

    'essage*oB.how+t.Totring+,,-%%Display type of varible

    'essage*oB.how+t.Name,-%%Display name of variable

    'essage*oB.how+t.Namespace,-%%Display namespace by name

    'essage*oB.how+t."sFrray.Totring+,,-%%Display boolean vale

    'essage*oB.how+t."s$lass.Totring+,,-%%Display boolean vale

    'essage*oB.how+t.'odle.Totring+,,-%%Display modle+library, of assembly

    'essage*oB.how+t.'emberType.Totring+,,-%%Display membertype by name

    'essage*oB.how+t.9etProperties+,.Totring+,,-%%Display property by name 'essage*oB.how+t.9etType+,.Totring+,,-%%Display type defined in assembly

    'essage*oB.how+t.9et'ethods+,.Totring+,,-%%Display method by name

    'essage*oB.how+t.9et"nterfaces+,.Totring+,,-%%Display interface by name

    'essage*oB.how+t.KllName.Totring+,,-%%Display type of variable by name

    'essage*oB.how+t.*aseType.Totring+,,-%%Display base type

    'essage*oB.how+t.Fttribtes.Totring+,,-%%Display attribte by name

    'essage*oB.how+t.Fssembly.Totring+,,-%%Display assembly by name

    'essage*oB.how+t.FssemblySalifiedName.Totring+,,-%%Display

    FssemblySalifiedName

    ystem.&eflection.Fssemblyo 8

    ystem.&eflection.Fssembly.Load+1mscorlib.dll1,- 'essage*oB.how+o.9etName+,.Totring+,,-%%Display information

    abot mscorlib assembly

    ob7ectob7 8 o.9etType+,-

    'essage*oB.how+ob7.Totring+,,-%%Display name of rntime assembly

    $onstrctor"nfo56 ci 8 t.9et$onstrctors+,-%%Display information abot

    constrctors

    foreach+$onstrctor"nfoi inci,

    0

    'essage*oB.how+i.Totring+,,-

    4

    'ethod"nfo56 mi 8 t.9et'ethods+,-%%Display information abot methods foreach+'ethod"nfoi inmi,

  • 7/24/2019 C# Notes.docx

    52/82

    0

    'essage*oB.how+i.Totring+,,-

    4

    Property"nfo56 pi 8 t.9etProperties+,-%%Display information abot properties

    foreach+Property"nfoi inpi,

    0 'essage*oB.how+i.Totring+,,-

    4

    'ember"nfo56 mf 8 t.9et'embers+,-%%Display information abot members

    foreach+'ember"nfoi inmf,

    0

    'essage*oB.how+i.Totring+,,-

    4

    Event"nfo56 ei 8 t.9etEvents+,-%%Display information abot events

    foreach+Event"nfoi inei,

    0

    'essage*oB.how+i.Totring+,,- 4

    Kield"nfo56 fi8 t.9etKields+,-%%Display information abot fields

    foreach+Kield"nfoi infi,

    0

    'essage*oB.how+i.Totring+,,-

    4

    4

    4

    4

    C7LLECTI7NS:

    Introduction

    "t is 7st li#e as array (bt always dynamic and can hold any vales nli#e array. "t is a

    data strctre that holds data in many different ways. The collection class is defined in

    the ystem.$ollections namespace. There are five types of collections in data strctre.

    .Hastable.Frraylist

    .Lin#edlist

    ;.tac#

    >.See

    *t mostly se of two types collections in $A(they are Hastable and Frraylist. Here we

    will discss abot only Hastable and Frraylist.

    .4 -astable

    Hastable have two vales i.e. #ey+id, and item+vale,.

  • 7/24/2019 C# Notes.docx

    53/82

    /hy we use -astable

    "f we want to stored data in two dimensional array at rn time then we se Hastable.

    Kor eBample( a months name and his serial nmber and we can access there data sing

    a #ey.

    singystem-

    singystem.$ollections.9eneric-

    singystem.$omponent'odel-

    singystem.Data-

    singystem.Drawing-

    singystem.LinJ-

    singystem.TeBt-

    singystem.Windows.Korms-

    singystem.$ollections-

    namespacehastable

    0 pblicpartialclassKorm: Korm

    0

    pblicKorm+,

    0

    "nitialiMe$omponent+,-

    4

    privatevoidKorm/Load+ob7ectsender( EventFrgse,

    0

    4

    privatevoidbtton/$lic#+ob7ectsender( EventFrgse,

    0 Hashtablehs 8 newHashtable+,-

    hs.Fdd+11( 1anary1,-

    hs.Fdd+11( 1Kebary1,-

    hs.Fdd+11( 1'arch1,-

    hs.Fdd+1;1( 1Fpril1,-

    hs.Fdd+1>1(1'ay1,-

    hs.Fdd+1=1( 17ne1,-

    hs.Fdd+1

  • 7/24/2019 C# Notes.docx

    54/82

    Now rn the application.

    !tpt +!ne vale sing #ey, loo#s li#e the below image.

    !tpt +all vales sing foreach loop, loo#s li#e the below image.

    code description

    "n the above code first of all we ma#e the ob7ect of hastable i.e. hs. Ffter that we addthe #ey and vale sing the hs ob7ect in the hastable. "f we print the only one vale thenwe will give yor #ey+id,( which is shown above. "f we print the all vales then we seforeach loop.

    54 Array+ist

    Frraylist have only one vales i.e. item+vale, not a #ey+id,.

  • 7/24/2019 C# Notes.docx

    55/82

    /hy we use Array+ist

    We #now that array have a fiBed siMe. "f we want to add items beyond the specifieddimension then we se Frraylist. "f we want to insert an item in a list then we se Lin#edlist bt in the $A we se Frraylist for that prpose.

    singystem-

    singystem.$ollections.9eneric-singystem.$omponent'odel-

    singystem.Data-singystem.Drawing-

    singystem.LinJ-singystem.TeBt-singystem.Windows.Korms-singystem.$ollections-namespacearraylist0 pblicpartialclassKorm: Korm

    0 pblicKorm+, 0

    "nitialiMe$omponent+,- 4

    privatevoidbtton/$lic#+ob7ectsender( EventFrgse, 0 FrrayListal 8 newFrrayList+,- al.Fdd+1anary1,- al.Fdd+1Kebary1,-

    al.Fdd+1'arch1,-

    al.Fdd+1Fpril1,- al.Fdd+1'ay1,- al.Fdd+17ne1,- al.Fdd+1ly1,- al.Fdd+1Fgst1,- al.Fdd+1eptember1,- al.Fdd+1!ctober1,- al.Fdd+1November1,- al.Fdd+1December1,-

    %%'essage*oB.how+al5?6.Totring+,,-%%Print the one vale

    foreach+string# inal,

    0 'essage*oB.how+#.Totring+,,-%% Print the all vales 4

    4

    4

    4

    Now rn the application.!tpt +!ne vale sing indeB nmber, loo#s li#e the below image.

  • 7/24/2019 C# Notes.docx

    56/82

    !tpt +all vales sing foreach loop, loo#s li#e the below image.

    3

    code description

    "n the above code first of all we ma#e the ob7ect of Frraylist i.e. )al). Ffter that we addthe vale sing the )al) ob7ect in the Frraylist. "f we print the only one vale then we willgive indeB nmber( which is shown above. "f we print the all vales then we se foreachloop.

    Summary

    Collections are very important for stored data in the array and list. $ollections solves themany problem li#e as fiBed array (lin#ed list etc. o collections are very sefl for solvingthese problems.

  • 7/24/2019 C# Notes.docx

    57/82

    ?ENE6ICS:

    Introduction:

    9enerics give yo the ability to create generic methods or a generic type by

    defining a placeholder for method argments or type definitions( that are

    specified at the time of invo#ing the generic method or creating the generic

    type.

    /hy 6enerics0

    To nderstand the importance of generics let)s start by seeing some #ind of

    problems that can be solved by them.

    Array+ist:

    Let)s start by creating an FrrayList to hold stac#allocated data.

    FrrayListintList 8 newFrrayList+,-

    Fs yo may #now( the FrrayList collection can receive and retrn only an

    !b7ect type( so the rntime will convert the vale type +stac#allocated,

    atomatically via boBing operation into an !b7ect +heapallocated, as in the

    following:

    FrrayListintList 8 newFrrayList+,-

    %%add a vale type to the collection+boBing,

    intList.Fdd+>,-

    To retrieve the vale from the FrrayList yo mst nboB the heapallocated

    ob7ect into a stac#allocated integer sing a casting operation.

    %%nboBing

    intB 8 +int,intList5?6-

    The problem with the stac#%heap memory transfer is that it can have a big

    impact on performance of yor application becase when yo se boBing and

    nboBing operations the following steps occr:

    . F new ob7ect mst be allocated on the managed heap.

    . The vale of the stac#allocated type mst be transferred into thatmemory location.

  • 7/24/2019 C# Notes.docx

    58/82

    @. When nboBed( the vale stored on the heap mst be transferred bac#

    to the stac#.

    . The nsed ob7ect on the heap will be garbage collected.

    Now consider that yor FrrayList contained thosands of integers that are

    maniplated by yor program( this for sre will have an affect on yor

    application performance.

    Custom Collections:

    Fssme that yo need to create a cstom collection that can only contain

    ob7ects of the Employee type.

    pblicclassEmployee

    0

    stringKirstName-

    stringLastName-

    intFge-

    pblicEmployee+,04

    pblicEmployee+stringfName( stringlName( intFge, 0

    this.Fge 8 Fge-

    this.KirstName 8 fName-

    this.Lastname 8 lName-

    4

    pblicoverridestringTotring+,

    0

    retrntring.Kormat+10?4 04 is 04 years old1( KirstName( LastName( Fge,-

    4

    4

    Now we will bild the cstom collection as in the following:

    pblicclassEmployees$ollection: "Enmerable

    0

    FrrayListalEmployees 8 newFrrayList+,-

    pblicEmployees$ollection+, 0 4

    %%"nsert Employee type pblicvoidFddEmployee+Employeee,

  • 7/24/2019 C# Notes.docx

    59/82

    0

    %%boBing

    alEmployees.Fdd+e,-

    4

    %%get the employee type

    pblicEmployee9etEmployee+intindeB,

    0

    %%nboBing

    retrn+Employee,alEmployees5indeB6-

    4

    %%to se foreach

    "Enmerator"Enmerable.9etEnmerator+,

    0

    retrnalEmployees.9etEnmerator+,-

    4

    4

    The problem here is that if yo have many types in yo application then yo

    need to create mltiple cstom collections( one for each type. Fnd as yo can

    see( we also have the problem of boBing and nboBing here.

    Fll problems yo saw previosly can be solved sing generics( so let)s seewhat we can do.

    (he System4Collections4generic namespace

    2o can find many generic collections in the ystem.$ollections.9eneric 7st

    li#e:

    . ListTI

    . DictionaryV( I

    . SeeTI

    ;. tac#TI

    9eneric collections allow yo to delay the specification of the contained type

    ntil the time of creation.

    *y sing the generic collection yo avoid performance problems of the

    boBing and nboBing operations and don)t need to create a cstom collection

  • 7/24/2019 C# Notes.docx

    60/82

    for each type in yo application.

    With the generic collections it)s p to yo to define the type that will be

    contained in the collection by replacing the placeholder T by the type yo

    want at the time of creation.

    +ist7(8

    The ListTI is a generic collection that represents a strongly typed list of

    ob7ects that can be accessed by indeB. "t is 7st li#e the nongeneric

    collection FrrayList.

    The following is an eBample of a ListTI:

    %%$an only contain int type

    ListintI intList 8 newListintI+,-

    %%no boBing

    intList.Fdd+?,-

    %%no nboBing

    intB 8 intList5?6-

    %%$an only contain Employee ob7ects

    ListEmployeeI empList 8 newListEmployeeI+,-

    %%no boBing

    empList.Fdd+newEmployee+1Fmr1( 1Fshsh1( ,,-

    %%no nboBing

    Employeee 8 empList5?6-

    9ueue7(8

    SeeTI is a generic collection that represents a firstin( firstot +K"K!,

    collection of ob7ects. "t is 7st li#e the nongeneric collection See.

    The following is an eBample of a SeeTI:

    %%F generic See collection

    SeeintI intSee 8 newSeeintI+,-

    %%Fdd an int to the end of the Jee

    %%+no boBing,

    intSee.EnJee+>,-

  • 7/24/2019 C# Notes.docx

    61/82

    %%&etrns the int at the beginning of the Jee

    %%withot removing it.

    %%+no nboBing,

    intB 8 intSee.Pee#+,-

    %%&emoves and retrns the int at the beginning of the Jee

    %%+no nboBing,

    inty 8 intSee.DeJee+,-

    Stac7(8

    tac#TI is a generic collection that represents a lastinfirstot +L"K!,

    collection of instances of the same arbitrary type. "t is 7st li#e the non

    generic collection tac#.

    The following is an eBample of a tac#TI:

    tac#intI inttac# 8 newtac#intI+,-

    %%"nsert an int at the top of the stac#

    %%+no boBing,

    inttac#.Psh+>,-

    %%&etrns the int at the top of the stac#

    %%withot removing it.

    %%+no nboBing,

    intB 8 inttac#.Pee#+,-

    %%&emoves and retrns the int at the top of the stac#

    %%+no nboBing,

    inty 8 inttac#.Pop+,-

    ictionary7,; '8

    DictionaryV( I is a generic collection that contains data in Vey%ale

    pairs( it is 7st li#e the nongeneric collection Hashtable.

    The following is an eBample of a DictionaryV( I:

    Dictionarystring( stringI dictionary 8 newDictionarystring( stringI+,-

    %%Fdd the specified #ey and vale to the dictionary

    dictionary.Fdd+1Vey1( 1ale1,-

  • 7/24/2019 C# Notes.docx

    62/82

    %%&emoves the vale with the specified #ey from the dictionary

    dictionary.&emove+1Vey1,-

    %%get the nmber of the Vey%ale pairs contained in the dictionary

    intcont 8 dictionary.$ont-

    B7=IN? AND

  • 7/24/2019 C# Notes.docx

    63/82

    (. inti @ (

    ). Arra$Listarrst @ ne%Arra$List34

    .

    /. //rray!ist contains ob"ect type value

    0. //So# int i is being created on heap

    1. arrst.Add3i4// Boxing occurs automatically

    .

    . int @ 3int4arrstFG// Unboxing occurs

    DI55E6ENCE BET2EEN ST6IN? AND ST6IN? Btrin)/tring is immutable, +mmutable means i$ you create string ob6ect then you cannotmodi$y it and +t always create new ob6ect o$ string type in memory.xamplestring str:yFalue 2 4Hello Fisitor47

    trin)b%ilder/tringuilder is mutable, means i$ create string builder ob6ect then you can per$orm anyoperation li'e insert, replace or append without creating new instance $or every time.itwill update string at one place in memory doesnt create new space in memory.xample/tringuilder sb:yFalue 2 new /tringuilder(44"7sb:yFalue.Append(4Hello Fisitor4"7sb:yFalue.Append(4How Are ou 554"7string str:yFalue 2 sb:yFalue.#o/tring("7

    PA6TIAL CLASSES:

    "t is possible to split the definition of a class or a strct( or an interface over two or more

    sorce files. Each sorce file contains a section of the class definition( and all parts are

    combined when the application is compiled.

  • 7/24/2019 C# Notes.docx

    64/82

    When wor#ing on large pro7ects( spreading a class over separate files allows mltiple

    programmers to wor# on it simltaneosly.

    When wor#ing with atomatically generated sorce( code can be added to the class

    withot having to recreate the sorce file. isal tdio ses this approach whencreating Windows Korms( Web ervice wrapper code( and so on. 2o can create code

    that ses these classes withot having to edit the file created by isal tdio.

    Exame

    # will de$elop an example that explains how to use a partial class in your pro-ect. (uppose

    you are wor6ing with L#NX to (XL in your application. (o you create a data context, in

    other words a .dml 7le and drag and drop the necessary tales. Each tale creates a

    partial class in the data context designer 7le and each tale 7eld ecomes a property orthe tale. (uppose you ha$e a ;8erson; tale that has the three 7elds ;#d;,;Name; and

    ;*ate)irth; and you want to show the age o each person in a grid $iew. What will you

    doQ # you add a new column to the tale or age in dataase or the ;8erson; tale then

    it ails the normaliation rule so you should not do that. # you add a new property to

    auto2generated code then it will not e mapped to the dataase. (o you need to create a

    partial class portion in a separate source 7le that has the ;Age; property. This ;Age;

    property calculates the age o the person when you ind a person list to the grid $iew.

    Let3s see each step2y2step.

    . !reate a ;8erson; tale in the dataase.

    Iou need to create a person tale in the dataase that has the three 7elds

    ;#d;,;Name; and ;*ate)irth;. The ;#d; 7eld is the primary 6ey.

    !0EATETA)LE8erson

    &

    #dintidentity&%,%'primary6ey,Namen$archar&K:',

    *ate)irth*atedeaultgetUtc*ate&'

    '

    . !reate a we application rom 4isual (tudio.

    @. 0ight2clic6 on the pro-ect in the (olution Explorer then go to ;Add; and clic6 on

    ;!lass;.

  • 7/24/2019 C# Notes.docx

    65/82

    . !hoose ;L#NX to (XL !lasses; rom the list and pro$ide the name ;8erson; or the

    *)"L name. Then clic6 on ;Add;.

    ?. *rag the User tale rom the dataase in the (er$er Explorer and drop onto theG0 *esigner surace o the ;8erson.dml; 7le.

    igure %./= 8erson entity

    Now you can open the ;8erson.designer.cs; 7le. #n the 7le the ;8erson; partial

    class has een created or drag and drops a ;8erson; tale rom dataase on

    G0" surace.

    I. !reate a partial class part that has the ;Age; property to calculate the age. This

    7le is named ;8ersonExtension.cs;.

    using(ystem>namespace8artial!lassExampleB pulicpartialclass8erson B pulicintAge B getB return!on$ert.To#nt?/&(ystem.*ateTime.UtcNow.*ate.Iear 2V*ate)irth.4alue.Iear'> C C C

    C

    J. !reate a U# design to show a person3s details in the grid $iew.

    YZ[8ageLanguageF;!D;AutoE$entWireupF;true;!ode)ehindF;8ersonU#.aspx.cs;#nheritsF;8artial!lassExample.8ersonU#;Z9

    Y\*!TI8Ehtml9YhtmlxmlnsF;http=GGwww.w?.orgG%]]]Gxhtml;9

    YheadidF;Head%;runatF;ser$er;9 Ytitle9YGtitle9

  • 7/24/2019 C# Notes.docx

    66/82

    YGhead9Yody9 YormidF;orm%;runatF;ser$er;9 Ydi$9 Yasp=Mrid4iew#*F;grid8erson;runatF;ser$er;9 YGasp=Mrid4iew9

    YGdi$9 YGorm9YGody9YGhtml9

    K. Write code or the ;8ageVLoad; e$ent to ind a grid $iew y person list in the code

    ehind 7le.

    using(ystem>

    using(ystem.Lin>namespace8artial!lassExampleB pulicpartialclass8ersonU#= (ystem.We.U#.8age B protected$oid8ageVLoad&o-ectsender, E$entArgs e' B using&8erson*ata!ontext context Fnew8erson*ata!ontext&'' B $aruery F romperson incontext.MetTaleY8erson9&' selectnew B person.#d,

    person.Name, person.*ate)irth, person.Age C> $arcontent F uery.ToList&'> grid8erson.*ata(ource F content> grid8erson.*ata)ind&'> C C CC

    L. 0un the application, you will see the Age column in the grid $iew that shows the

    age o each person. Let3s see that in igure %.?.

  • 7/24/2019 C# Notes.docx

    67/82

    INDE=E6S

    "ndeBer allows classes to be sed in more intitive manner. $A introdces a new concept#nown as "ndeBers which are sed for treating an ob7ect as an array. The indeBers are

    sally #nown as smart arrays in $A. They are not essential part of ob7ectoriented

    programming.

    Fn indeBer( also called an indeBed property( is a class property that allows yo to access

    a member variable of a class sing the featres of an array.

    Defining an indeBer allows yo to create classes that act li#e virtal arrays. "nstances of

    that class can be accessed sing the 56 array access operator.

    Creating an Inde$er

    modifierI retrntypeI this5argment list6

    0

    get

    0

    %% yor get bloc# code

    4

    set

    0

    %% yor set bloc# code

    4

    4

    "n the above code:

    7modifier8can be private( pblic( protected or internal.

  • 7/24/2019 C# Notes.docx

    68/82

    7returntype8

    can be any valid $A types.

    thisthis is a special #eyword in $A to indicate the ob7ect of the crrent class.

  • 7/24/2019 C# Notes.docx

    69/82

    0

    privatestring56 names 8 newstring5?6-

    pblicstringthis5inti6

    0 get

    0

    retrnnames5i6-

    4

    set

    0

    names5i6 8 vale-

    4

    4

    4

    staticvoid'ain+string56 args,

    0

    "ndeBer$lassTeam 8 new"ndeBer$lass+,-

    Team5?6 8 1&oc#y1-

    Team56 8 1Teena1-

    Team56 8 1Fna1-

    Team56 8 1ictoria1-

    Team5;6 8 12ani1- Team5>6 8 1'ary1-

    Team5=6 8 19omes1-

    Team5

  • 7/24/2019 C# Notes.docx

    70/82

    "ndeBers are created with this

    #eyword.

    Properties don)t reJire this

    #eyword.

    "ndeBers are identified by signatre. Properties are identified by their

    names.

    "ndeBers are accessed sing

    indeBes.

    Properties are accessed by their

    names.

    "ndeBer are instance member( so

    can)t be static.

    Properties can be static as well as

    instance members.

    F get accessor of an indeBer has the

    same formal parameter list as theindeBer.

    F get accessor of a property has no

    parameters.

    F set accessor of an indeBer has the

    same formal parameter list as the

    indeBer( in addition to the vale

    parameter.

    F set accessor of a property

    contains the implicit vale

    parameter.

    "ndeBers are commonly sed for classes( which represents some data strctre( an

    array( list( map and so on.

    SEALED CLASS & SEALED MET>7DS:

    >ealed Class

    /ealed class is used to de$ine the inheritance level o$ a class.

    #he sealed modi$ier is used to prevent derivation $rom a class. An error occurs i$ a sealed class is

    speci$ied as the base class o$ another class.

    >ome points to remember:

    . A class, which restricts inheritance $or security reason is declared, sealed class.

    . /ealed class is the last class in the hierarchy.

    @. /ealed class can be a derived class but canMt be a base class.

  • 7/24/2019 C# Notes.docx

    71/82

    . A sealed class cannot also be an abstract class. ecause abstract class has to

    provide $unctionality and here we are

    restricting it to inherit.

    Practical demonstration of sealed class

    using(ystem>using(ystem.!ollections.Meneric>using(ystem.Lin>using(ystem.Text>namespacesealedVclassB class8rogram

    B pulicsealedclass)ase!lass B pulic$oid*isplay&' B !onsole.WriteLine&;This is a sealed class which can>t e urtherinherited;'> C C

    pulicclass*eri$ed= )ase!lass

    B GG this *eri$ed class can>t inherit )ase!lass ecause it is sealed C

    static$oid"ain&stringS args' B )ase!lasso- Fnew)ase!lass&'>

    o-.*isplay&'>

    !onsole.0eadLine&'> C CC/ealed :ethods/ealed method is used to de$ine the overriding level o$ a virtual method./ealed 'eyword is always used with override 'eyword.Practical demonstration of sealed method

    using(ystem>using(ystem.!ollections.Meneric>

  • 7/24/2019 C# Notes.docx

    72/82

    using(ystem.Lin>using(ystem.Text>namespacesealedVmethodB

    class8rogram B pulicclass)ase!lass B

    pulic$irtual$oid*isplay&' B !onsole.WriteLine&;4irtual method;'> C C

    pulicclass*eri$ed!lass=)ase!lass B GG Now the display method ha$e een sealed and can>t e o$erridden pulico$erridesealed$oid*isplay&' B !onsole.WriteLine&;(ealed method;'> C C

    GGpulic class Third!lass = *eri$ed!lass GGB

    GG pulic o$erride $oid *isplay&' GG B GG !onsole.WriteLine&;Here we try again to o$erride display methodwhich is not possile and will gi$e error;'> GG C GGC

    static$oid"ain&stringS args' B

    *eri$ed!lasso% Fnew*eri$ed!lass&'>

    o%.*isplay&'>!onsole.0eadLine&'>

    C CC

    5ILE IH7 :

  • 7/24/2019 C# Notes.docx

    73/82

    &ile handling is a very crucial and important $eature $or many enterprise applications

    around us. #o support this $eature :icroso$t .%E# &ramewor' o$$ers the /ystem.+

    namespace, that provides various classes to enable the developers to do +

    #he 4!eadAllines4 method reads all the contents o$ a $ile and stores each line at

    a new inde) in an array o$ string type.

    string7le8ath F [;!="y*ataTestile.txt;>

  • 7/24/2019 C# Notes.docx

    74/82

    stringS test*ataLine)yLine F ile.0eadAllLines&7le8ath'>

    #he 4!eadAllytes4 method reads the contents o$ a $ile as binary data and stores

    the data in a byte array.

    string7le8ath F [;!="y*ataTestile.txt;>

    yteS test*ata0aw)ytes F ile.0eadAll)ytes&7le8ath'>

    Each o$ these methods enable the developer to read the contents o$ a $ile and load into

    memory. #he !eadAll#e)t method will enable the developer to cache the entire $ile in

    memory via a single operation. Whereas the !eadAllines method will read line-by-line

    into an array.

    =ritin) ata to ;> ile.WriteAllText&7le8ath, data'>

    #he 4WriteAllines4 method enables the developers to write the contents o$ a

    string array to a $ile. Each entry in the string array will be a new line in the new

    $ile.

    string7le8ath F [;!="y*ataTestile.txt;>

    stringS data F B ;"!T;, ;"!8*;, ;"!T(;, ;"!(*.NET;, ;"!A*.NET;, ;!(";C>

    ile.WriteAllLines&7le8ath, data'>

  • 7/24/2019 C# Notes.docx

    75/82

    #he 4AppendAll#e)t4 method enables the developers to write the contents o$ a

    string variable at the end o$ an e)isting $ile.

    string7le8ath F [;!="y*ataTestile.txt;>

    stringdata F ;Also !erti7ed rom ##T ile.AppendAllText&7le8ath, data'>

    #he 4AppendAllines4 method enables the developers to write the contents o$ a

    string array to the end o$ an e)isting $ile.

    string7le8ath F [;!="y*ataTestile.txt;>

    stringS other*ata F B ;Wor6ed with "icrosot;, ;Li$ed in U(A;C>

    ile.AppendAllLines&7le8ath, other*ata'>

    /ote:#he overwrite parameter passed to the Copy method call indicates that the copy

    process should overwrite an e)isting $ile i$ it e)ists at the destination path. +$ you pass

    $alse to the Copy method call, and the $ile already e)ists then the Common anguage

    !untime (C!" will throw a /ystem.+.+E)ception.

    #he 40elete4 method deletes an e)isting $ile $rom the $ile system.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

  • 7/24/2019 C# Notes.docx

    76/82

    ile.*elete&sourceile8ath'>

    #he 4E)ists4 method chec's whether a $ile e)ists on the $ile system.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

    ooldoesileExist F ile.Exists&sourceile8ath'>

    #he 4GetCreation#ime4 method obtains the date time stamp that describes when

    a $ile was created, $rom the metadata associated with the $ile.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

    *ateTime7le!reatedn F ile.Met!reationTime&sourceile8ath'>

    0sin)

    stringdestinationile8ath F [;!=temp*ata.txt;>

    oolo$erwrite F true>

    ile#no#no F newile#no&sourceile8ath'>

    #no.!opyTo&destinationile8ath, o$erwrite'>

    /oteO #he overwrite parameter in the Copy#o method indicates that the copy process

    should overwrite an e)isting $ile i$ it e)ists at the speci$ied destination $ile path. +$ you

    pass $alse to the Copy#o method, and the $ile already e)ists then the C! will throw a

    /ystem.+.+E)ception.

  • 7/24/2019 C# Notes.docx

    77/82

    #he 40elete4 method enables the developers to delete a $ile.

    stringsourceile8ath F [;!="y*ataTestile.txt;>ile#no#no F newile#no&sourceile8ath'>

    #no.*elete&'>

    #he 40irectory%ame4 property enables the developers to get the directory path to

    the $ile.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

    ile#no#no F newile#no&sourceile8ath'>

    stringdirectory8ath F #no.*irectoryName>

    GG returns !="y*ata

    #he 4E)ists4 method enables the developers to determine i$ the speci$ied $ile

    e)ists within the $ile system.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

    ile#no#no F newile#no&sourceile8ath'>

    ool7lesExists F #no.Exists>

    #he 4E)tension4 property enables you to get the $ile e)tension o$ a $ile.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

    ile#no#no F newile#no&sourceile8ath'>

    ool7lesExtn F #no.Extension>

    #he 4ength4 property enables the developers to get the length o$ the $ile in

    bytes.

    stringsourceile8ath F [;!="y*ataTestile.txt;>

    ile#no#no F newile#no&sourceile8ath'>

    longlength F #no.Length>

    irectory'n$o and irectory class to anip%latin) irectories

    +n an operating systemNs $ile system, the $iles are organiBed into directories. Hence, it is

    very crucial $or an application to interact and manipulate the $ile systemNs directory

    structure. +nteraction with directories may include chec'ing that a directory e)ists be$ore

    writing a $ile or to remove directories a$ter the process is complete as a cleanup policy.

  • 7/24/2019 C# Notes.docx

    78/82

    #he .%E# &ramewor' class library provides the 0irectory and 0irectory+n$o classes $or

    such operations.

    0sin) irectory class to manip%late directories

    /imilar to the &ile class, the 40irectory4 class provides static methods that enable you to

    interact with directories, without instantiating a directory-related ob6ect in your code.

    #he 4Create0irectory4 method creates a new directory on the $ile system.

    stringsource*ir8ath F [;!="y*ata*ata;>

    *irectory.!reate*irectory&source*ir8ath'>

    #he 40elete4 method deletes a directory at a speci$ic path.

    stringsource*ir8ath F [;!="y*ata*ata;>

    ooldelete0ecursi$ely F true>

    *irectory.*elete&source*ir8ath, delete0ecursi$ely'>

    /oteO #he delete!ecursively parameter passed into the 0elete method speci$ies

    whether the delete process should delete any content that may e)ist in the

    directory. +$ you pass $alse into the 0elete method, and the directory is not empty

    then the C! will throw a /ystem.+.+E)ception.P

    #he 4E)ists4 method determines i$ a directory e)ists on the $ile system.

    stringsource*ir8ath F [;!="y*ata*ata;>

    ooltemp*ata*irectoryExists F *irectory.Exists&source*ir8ath'>

    #he 4Get0irectories4 method gets a list o$ all subdirectories within a speci$ic

    directory on the $ile system.

    stringsource*ir8ath F [;!="y*ata*ata;>

    stringS su*irectories F *