csharp tutotial

Upload: orhan-bakalli

Post on 05-Apr-2018

322 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 csharp tutotial

    1/52

    C# Tutorial

    Orhan R Bakalli

  • 7/31/2019 csharp tutotial

    2/52

    C# Tutorial Futja e kuadrit. NET Krahasimi C # pr C + + dhe Java T'ia

    Fillohet Llojet ndryshueshme vargjeve operatort Kontrolli Flow

    Klasat futur, strukturave dhe hapsira Deklarata Class MetodatFutja Polymorphism (Metodat e trashguara) Konstante, fusha,Prona dhe Indexers Delegatt dhe Ngjarje prjashtimeDokumentacioni Kodi

  • 7/31/2019 csharp tutotial

    3/52

    Introducing the Microsoft .NET Framework

    NET (dot-net) Fillon Ime i Microsoft i JEP vizionin e saj

    te prgjithshm te ardhmen e informatik, pamje te qenite Nje Bote ne te ciln shume aplikacione drejtuar nemnyr te shprndar npr internet. Ne ndjekse teidentifikojn Nje numr te motiveve te ndryshme lvizse

    Kete Vizion. Programimi object-oriented Prpiluar Njektu Barbie te kandidoj Kudo. Shrbimi i orientuar drejtaplikimit. NET Fillon Microsoft JVM? . NET Ka qen endrtuar MBI teknologjit e Hapur Standardizimi si XML

    Barbie SOAP Barbie Fillon drejt standardeve Datlindjate Hapur ne Vend se tendenca e Microsoft tij tepronarit.Undo redaktimet

  • 7/31/2019 csharp tutotial

    4/52

    Introducing the Microsoft .NET Framework

    N fund zhvillimin e vizionit sht NET NET Framework

    (Microsoft JDK?) Q prmban.:Gjuh e prbashkt,. NET KornizKlast, dhe nivelit m t lart karakteristika si ASP.NET dheWinForms pr zhvillimin e aplikacioneve desktop.RuntimeCommon Language (CLR) (Microsoft JRE?) Menaxhon zbatimin ekodit t hartuar pr platforma. NET.CLR ka dy karakteristika:Specifikimi i saj ka qen e hapur n mnyr q t mund t ported

    jo-Windows platformat. do numr i gjuhve t ndryshme mund tprdoret pr t manipuluar. NET klasa kuadr, dhe CLR do tmbshtes ato.

  • 7/31/2019 csharp tutotial

    5/52

    C#

    Jo t gjitha gjuht e mbshtetur t prshtatet trsisht me kujdes n

    kuadrin. NET, por nj gjuh q sht e garantuar pr t prshtatenn mnyr t prkryer sht C #. C # (C Sharp), nj pasues t C ++, sht liruar n lidhje me kuadrin. NET. C dizajn Qllimet msgstrme: Jet t rehatshme pr C + + programues Fit pastr n. RuntimeNET Gjuhsh e prbashkta CLR) Thjeshtoj C + modelin + E Tsiguroj sasi t drejtn e fleksibilitetit Komponent-centricmbshtetje t zhvillimitUndo edits

  • 7/31/2019 csharp tutotial

    6/52

    C# versus Java (Similarity) C # dhe Java jan dy gjuh t zbritur nga C dhe C + +. do

    prfshin veori t prparuara, si grumbullimin e mbeturinave, tcilat hequr disa prej detyrave t ult t mirmbajtjes t nivelit ngaprogramues. N shum fusha ato jan sintaktikisht t ngjashme.Both # C dhe Java hartuar fillimisht me nj gjuh t ndrmjetme: C# pr Microsoft Intermediate gjuhn (MSIL), dhe Java n Java

    bytecode. N do rast gjuha e ndrmjetme mund t kandidoj - meinterpretimin ose thjesht-n-koh prpilimin - n nj makin tprshtatshme virtuale. N C #, megjithat, m sht dhnmbshtetje pr hartimin e mtejshm t kodit gjuhn ndrmjetmen kodin amtare. Ashtu si Java, C # i jep dor nga trashgimi klas

    t shumta n favor t nj modeli trashgimi t vetme. C # mbshtettrashgimi t shumta e interfaces.

  • 7/31/2019 csharp tutotial

    7/52

    C# versus Java (Differences) C # prmban tipe primitive t dhnave m shum se Java,

    dhe gjithashtu lejon zgjerim m shum pr llojet vler.Pr shembull, C # mbshtet enumerations, t tipit tsigurta llojet me vler t cilat jan t kufizuara pr njgrup t definuar t variablave t vazhdueshme, dhestructs, t cilat jan prdorues t prcaktuara lloje vler.

    Java nuk ka enumerations, por mund t specifikoni njklas t imitojn ato. Ndryshe nga Java, C # ka funksiont dobishme q ne mund t mbingarkoj operatorve tndryshme. Megjithat, polymorphism sht trajtuar nnj mnyr m t komplikuar, me rregulla t nxjerra n

    klas ose thelbsore ose fshehur metoda super klass. NJava, multi-dimensionale vargjeve jan zbatuar vetm menj-dimensionale vargjeve ku vargjeve mund t jenantar t vargjeve t tjera. Prve vargjeve tdhmbzuar, megjithat, C # edhe zbaton vargjeve t

    vrtet drejtkndshe.

  • 7/31/2019 csharp tutotial

    8/52

    C# versus C++ (Differences) C # prdor delegat - lloj-pointers t sigurta metod.

    Kto jan prdorur pr t zbatuar ngjarje trajtimin-. Edhepse ka disa elemente q rrjedhin nga Visual Basic dheJava, C + + eshte C # 's relative afrt. N nj ndryshim trndsishm nga C + +, C # Kodi nuk krkon fotografititull. T gjitha Kodi sht shkruar Inline.. NET Runtime

    n t cilat C # drejton kryen menaxhimin e kujtesskujdeset pr detyrat si grumbullimin e mbeturinave. Prshkak t ksaj, prdorimi i pointers n C # sht shumm pak e rndsishme se n C + +. Pointers mund tprdoret n C #, ku kodi sht shnuar si i pasigurt, por

    ato jan vetm t vrtet t dobishme n situata ku fitimete performancs jan n nj fitim absolut. N prgjithsi,t gjitha llojet msgstr C rrjedh prfundimisht nga lloji iobjektit.Undo edits

  • 7/31/2019 csharp tutotial

    9/52

    C# versus C++ (Differences) Ka edhe dallime t veanta n mnyr q lloje t caktuara

    t prbashkta mund t prdoren. Pr shembull, Cvargjeve msgstr jan kufijt kontrolluar ndryshe n C ++, dhe kjo nuk sht e mundshme, pra pr t shkruar ekaluara n fund t nj sr C #. C deklaratat msgstr jan

    mjaft t ngjashme me C + + pasqyra. T prmendetvetm nj shembull t nj ndryshim: Deklaratat e'ndrprersin' ka ndryshuar n mnyr q sjellja 'bien-prmes' nuk lejohet. Si u prmend m lart, C # jep derin iden e trashgimis klass s shumfisht. Dallime ttjera q lidhen me prdorimin e klasave jan: nuk shtmbshtetje pr 'Properties' klasn e llojit t gjetur nVisual Basic, dhe metodat e klass jan quajtur prdorur.Operatori sesa :: operator.Undo edits

  • 7/31/2019 csharp tutotial

    10/52

    Getting StartedHello World! N mnyr q t prdorni C # dhe klasa. NET

    Framework, s pari instaloni. SDK NET Framework. Write the C# code.using System;public class HelloWorld {

    public static void Main() {// This is a single line comment./*

    * This is a multiple line comment.*/

    Console.WriteLine("Hello World!");}

    }

    To compile the program on Mono, use the command:mcs HelloWorld.cs (csc HelloWorld.cs in .NETframework SDK)

    To run the program on Mono: mono HelloWorld.exe

  • 7/31/2019 csharp tutotial

    11/52

    Variable Types C # sht nj lloj i sigurt-gjuha. Variablat jan deklaruar

    si t nj lloji t veant, dhe secili variabl sht edetyruar t mbaj vetm vlerat e llojit t saj t deklaruar.Variablat mund t mbaj as lloje vler ose llojet ereferencs, apo ato mund t jen pointers. Nj variabl e

    llojeve me vler drejtprdrejt prmban vetm nj objektme vler. Nj variabl e tipit reference direkt prmbannj referenc n nj objekt. Nj tjetr shum tndryshueshme t prmbaj nj referenc pr t njjtinobjekt. sht e mundur n C # pr t prcaktuar llojet etuaja me vler duke deklaruar enumerations ose structs.

  • 7/31/2019 csharp tutotial

    12/52

    C# Pre-defined Value TypesC# Type .Net Framework Type Signed Bytes Possible Values

    sbyte System.sbyte Yes 1 -128 to 127

    short System.Int16 Yes 2 -32768 to 32767

    int System.Int32 Yes 4 231 to 231 - 1

    long System.Int64 Yes 8 263 to 263 - 1

    byte System.Byte No 1 0 to 255

    ushort System.Uint16 No 2 0 to 65535

    uint System.Uint32 No 4 0 to 232 - 1

    ulong System.Uint64 No 8 0 to 264 - 1

    float System.Single Yes 4 1.5 x 10-45 to 3.4 x 1038 with 7

    significant figuresdouble System.Double Yes 8 5.0 x 10-324 to 1.7 x 10308 with 15 or

    16 significant figures

    decimal System.Decimal Yes 12 1.0 x 10-28 to 7.9 x 1028 with 28 or 29significant figures

    char System.Char N/A 2 Any Unicode character

    bool System.Boolean N/A 1/2 true or false

  • 7/31/2019 csharp tutotial

    13/52

    Value Types Llojet Vlera: int x = 10; Llojet e referencs: llojet e reja t referencs mund t

    prcaktohet duke prdorur 'klass', 'Te ndrfaqe', dhe '' t deleguardeklaratat objekt. Objekti x = objekt i ri (); x.myValue = 10; Ikni sekuencadhe strings fjal pr fjal string a = "\" Hello World \ nHow jeni \ ""; Boks: C #

    ju lejon t konvertohet do lloj vler t nj lloji prkats referimi, dhe pr tkthyer rezultate s Gallery Boxed 'Tipi prsri. int i = 123; kuti objekt = i; if(kutia sht int) {Console.Write ("Kutia prmban nj int");} / / kjo linj sht e

    shtypurUndo edits

  • 7/31/2019 csharp tutotial

    14/52

    Pointers Nj tregues sht nj ndryshore q mban adresn e

    kujtess s nj lloji tjetr. N C #, pointers mund tdeklarohet pr t mbajtur adresat e memories t llojevet vler. Pointers jan deklaruar n mnyr implicite,duke prdorur simbol dereferencer shtypur *.Operatori& kthen kujtess adresn e vete prefikset ndryshueshme.Shembull: Cila sht vlera e un? int i = 5; int *p; p = &i; * p = 10;Prdorimi i pointers sht ikufizuar pr kodin i cili sht shnuar si i pasigurt (hyrjekujtess).Undo edits

  • 7/31/2019 csharp tutotial

    15/52

    Pointers Pr t adresuar problemin e grumbullimit t mbeturinave,

    mund t deklaroj nj tregues brenda nj shprehje tcaktuar. do lloje t vlers s deklaruar brenda kodit tpasigurt jan fikse automatikisht, dhe do t gjenerojprpilojn me koh gabime n qoft se prdoren brendashprehjeve fikse. E njjta gj nuk sht e vrtet pr lloje

    t referencs. Edhe pse zakonisht pointers mund tprdoren vetm me lloje t vler, nj prjashtim nga kjoprfshin vargjeve. Nj tregues mund t deklarohet nlidhje me nj grup, si n vijim: int [] = {a 4, 5}; int *

    b = a; far ndodh n kt rast sht se vendndodhja ekujtess mban b sht vend i llojit t par t mbajtur nganj.

  • 7/31/2019 csharp tutotial

    16/52

    Arrays Single-dimensional arrays have a single dimension

    int[] i = new int[100]; C# supports two types of multidimensional arrays:

    rectangular and jagged. A rectangular array is a multidimensional array that has the

    fixed dimensions' sizes.int[,] squareArray = new int[2,3];

    int[,] squareArray = {{1, 2, 3}, {4, 5, 6}};

    Ajagged arrays is a multidimensional array that has the

    irregular dimensions sizes.int[][] jag = new int[2][];

    jag[0] = new int [4];

    jag[1] = new int [6];

    int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}};

  • 7/31/2019 csharp tutotial

    17/52

    Enumerations Nj regjistrimit sht nj lloj i veant i llojit t vlers s kufizuar

    n nj grup t kufizuar dhe t pandryshueshme t vleravenumerike. Kur ne t prcaktoj nj numrimit q ne ofrojmliterals t cilat jan prdorur m pas si kosntanta pr vlerat e tyreprkatse.Kodi i mposhtm tregon nj shembull t till njprkufizim: DITT publike enum {hn, e mart, e mrkur, e

    enjte, e premte, e shtun, e diel}; enum byteEnum: bajt {A, B};N vend t ksaj, vlerat numerike jan ngritur n prputhje me ktody rregulla: Pr literal i par: nse ajo sht e unassigned, pr tprcaktuar vlern e saj n 0. Pr do literal tjetr: nse ajo sht eunassigned, pastaj vendoset vlern e saj n nj m t madhe se

    vlera e literal msiprm.

  • 7/31/2019 csharp tutotial

    18/52

    Enumerationsusing System;public class EnumTest {

    public enum DAYS: byte{Monday, Tuesday, Wednesday, Thursday, Friday,Saturday, Sunday};

    public static void Main() {Array dayArray =Enum.GetValues(typeof(EnumTest.DAYS));

    foreach (DAYS day in dayArray)Console.WriteLine("Number {1} of EnumTest.DAYS is {0}",

    day, day.ToString("d"));}

    }

  • 7/31/2019 csharp tutotial

    19/52

    Enumerations Console.WriteLine("Number {1} of EnumTest.DAYS is {0}",

    day, day.ToString("d"))

    is equivalent to:Console.WriteLine(String.Format("Number {1} ofEnumTest.DAYS is {0}", day, day.ToString("d")));

    And what the String.Format method does is to take

    textual representations of the objects it is passed asparameters, and slots them into the appropriate placeswithin the format string it is passed. So this line of codeis basically equivalent to:Console.WriteLine("Number " + day.ToString("d").ToString()+ " of EnumTest.DAYS is " + day.ToString());

    The ToString method can take a singleIFormatProvider parameter which indicates how thestring conversion should be conducted. Values for this

    parameter can include things like g, d, x, f, etc.

  • 7/31/2019 csharp tutotial

    20/52

    Operators C# has a number of standard operators, taken from C,

    C++ and Java. Most of these should be quite familiar toprogrammers.

    To overload an operator in a class, one defines a methodusing the operator keyword. For instance, the followingcode overloads the equality operator.

    public static bool operator == (Value a, Value b) {

    return a.Int == b.Int

    }

    Where an operator is one of a logical pair, both operatorsshould be overwritten if any one is.

  • 7/31/2019 csharp tutotial

    21/52

    Jump and Selection Statements Deklarata pushim shprthen nga koh dhe pr

    sythe.Deklarata vazhdojn mund t vendoset n dostruktur loop.Deklarata goto sht prdorur pr t brnj krcim n nj pjes t veant emrtuar t kodit tprogramit. Nse-tjetr deklaratat jan prdorur pr tkandiduar blloqe t kodit t kushtzuar me nj shprehjeboolean vlersues t vrtet. Deklaratat Switch ofrojnnj mnyr t pastr e t shkruarit t shumta, nse -

    deklaratat tjetr.Undo edits

  • 7/31/2019 csharp tutotial

    22/52

    Loop Statements while loops

    while (expression) statement[s] do-while loops

    do statement[s] while (expression)

    for loopsfor (statement1; expression; statement2) statement[s]3

    foreach loops

    foreach (variable1 in variable2) statement[s]int[] a = new int[]{1,2,3};

    foreach (int b in a)

    System.Console.WriteLine(b);

  • 7/31/2019 csharp tutotial

    23/52

    Classes and Structs Klasat siguroj templates nga e cila objekte - shembuj t

    ktyre klasave, mund t gjenerohet. Nj klas especifikon nj tip dhe elementeve konstituive (antarttipit) t atij lloji. Nj klas mund t specifikoni dy llojekryesore t antarve t tipit: Nj klas mund t saktsoj

    llojet e tjera - si vler dhe referenc. Llojet mund tprmbaj lloje tjera, q sht i njohur si frenimin, osetjetr t bashkimit. Nj klas mund t specifikoj metodat- funksionet e projektuar pr leximin dhe manipulimin evlers dhe llojet e referencs nj shembull prmban. Cklasa msgstr mund t trashgojn nga nj klas baz tvetme ose nga ndonj numr t interfaces.

  • 7/31/2019 csharp tutotial

    24/52

    Namespaces Namespaces can be thought of as collections of classes;

    they provide unique identifiers for types by placing themin an hierarchical structure.

    To use theSystem.Security.Cryptography.AsymmetricAlgorithm class,specify it in the following statement:

    using System.Security.Cryptography; An alias for the namespace can be specified as using

    myAlias = System.Security.Cryptography; For instance, the following code states that the class

    Adder is in the namespace fred.math.namespace fred {

    namespace math {public class Adder { // insert code here }

    }

    }

  • 7/31/2019 csharp tutotial

    25/52

    Class Declaration Class declarations can have up to four different parts,

    surrounding the class keyword:attributes class-modifiers class class-base class-body

    The class-body element specifies type members. Thefollowing is an example of a class declaration:public class Shape {

    // class-body

    }

    Attributes can be posted at the front of a classdeclaration. These comprise user-defined meta-dataabout the class; information which can be brought out atruntime.

  • 7/31/2019 csharp tutotial

    26/52

    Class Declaration Ka shtat t ndryshme - optional - modifiers klass. Katr nga

    kto - publik, t brendshm, t mbrojtur, dhe private - janprdorur pr t prcaktoj nivelet e aksesit t llojeve tprcaktuara nga klasat.Fjalen publik identifikon nj lloj siplotsisht t arritshme pr t gjitha llojet e tjera. Nse nj klassht deklaruar si t brendshme, tip ajo definon sht i arritshm

    vetm pr llojeve brenda kuvendit njjtin nj vet-prmbante 'njsie paketimit' kodi prmban, metadata etj.) Nse nj klas shtshpallur e mbrojtur, llojin e saj sht e arritshme nga nj lloj qprmbajn dhe do lloji q trashgon nga ky lloj prmban. Kur njklas sht deklaruar si private, qasja n llojin ajo definon sht i

    kufizuar n nj lloj q prmban vetm.

  • 7/31/2019 csharp tutotial

    27/52

    Class Declaration Lejet e lejuara nga brendshme t mbrojtura jan ato t

    lejuara nga niveli i mbrojtur plus ato t lejuara nganiveli i brendshm.Fjalen e re mund t prdoret prklasat e mbivendosur. Nj klas deklarohen si abstraktenuk mund vet t instanced - ajo sht projektuar vetmpr t qen nj klas baz pr trashgim. Nj klas eshpallur si t mbyllur nuk mund t trashgohetnga.Undo edits

  • 7/31/2019 csharp tutotial

    28/52

    Class Declaration Baza klas pjes e deklarats klass specifikon emrin e

    klass dhe t gjitha klasa q ai trashgon nga.Linja mposht deklaron nj klas publik t quajturDrawingRectangle q trashgon nga drejtkndshklass baz dhe vizatim

    ndrfaqes: DrawingRectangle publik klas:Rectangle, Vizatim Interfaces jan deklaruar n tnjjtn mnyr si klasa standarde, prve se ataprdorin ndrfaqe fjalen n vend t klass fjalen. Prshembull: Vizatim publik ndrfaqe

  • 7/31/2019 csharp tutotial

    29/52

    Methods Metodat jan operacione q lidhen me llojet. int

    shuma = Arithmetic.addTwoIntegers (4, 7); Njdeklarat e metod, t specifikuara n nj deklarat tklass, prbn nj metod kok-dhe nj metod-trup.Metoda e-kreu sht i prbr nga elementet e

    mposhtme (kllapa katrore fus ato t cilat janopsionale). [atribute] [metod t modifiers] kthimit-llojmetoda-name ([formal-parametr-list]) Atributet Metodat punoj n nj mnyr t ngjashme me ato t klasave.

  • 7/31/2019 csharp tutotial

    30/52

    Methods Ka dhjet modifiers metod q mund t prdoren. Katr nga

    kto jan modifiers qasje q mund t prdoren n deklaratat eklass. Kto pun katr analoge pr mnyrn se si ata punojnn deklaratat e klass. T tjert jan si m posht: Abstract: Njmetod pa specifikuar trupin e saj. Metoda t tilla jan vetquajtur abstrakte. Nj klas prmban nj metod abstrakt ai nuk

    mund t instantiated.Modifier statike deklaron nj metod tjet nj metod klas (nj metod q mund t prdoret pa njshembull). Hapsira t meta Paketat n Java) mund t mendohetsi koleksionet e klasave, ata japin identifikues unik pr llojeduke i vendosur ato n nj struktur hierarkike.Undo edits

  • 7/31/2019 csharp tutotial

    31/52

    Polymorphism (Inherited Methods) C # mbshtet dy mnyra t ndryshme t metods

    overwriting - fshehja ose thelbsore. Vini re se termi"prishsh 'sht nj term i kemi shpikur pr t mbuluar tdyja fshehur dhe mbizotruese. Overwriting metod ebn prdorimin e mposhtme tri metoda me kok fjalkye: ri, virtual, refuzo Dallimi kryesor n mes tfshehur dhe thelbsor ka t bj me zgjedhjen e cilametod pr t thirrur, ku klasa e deklaruar e nj

    ndryshore sht e ndryshme n klas drejtuar me koh tobjektit ajo referencat.Undo edits

  • 7/31/2019 csharp tutotial

    32/52

    Constants, Fields, Properties and Indexers Fushat jan variabla q lidhen me ose klasa ose rastet e klasave.

    Ka shtat modifiers t cilat mund t prdoren n deklaratat e tyre.Kto prfshijn Ndryshuesit katr qasje publike, t mbrojtur, tbrendshm dhe privat dhe fjalen e re. T dy modifiers mbetura

    jan: Static: By default, fusha jan t lidhura me raste t klass.Prdorimi i fjalen statike, megjithat, bashkpuntort nj fush

    me nj klas n vetvete, kshtu q nuk do t vetm ndonjher tjet nj fush e till n klas, pavarsisht nga numri i rasteve tklass. Readonly: Kur nj fush sht Readonly, vlera e tij mundt vendosen vetm nj her.

  • 7/31/2019 csharp tutotial

    33/52

    Constants, Fields, Properties and Indexers Konstantet jan t llojeve t pandryshueshme, t

    shoqruara me klasa, t cilat jan t qasshme n kohn ekompilimit. Pr shkak t ktij fakti t fundit, konstantamund t jet vetm lloje vler sesa llojet ereferencs. publik const int Zona e = 4; Prona t

    paluajtshme mund t mendohet si fusha virtuale. Ngajasht, pron e nj klasa! Duket vetm si nj fush. Pornga brenda, prona sht prodhuar duke prdorur fushataktuale t klass. Nse pronat jan fusha virtuale,

    indexers jan m shum si vargjeve virtuale. Ato lejojnnj klas t matem nj koleksion, ku elementt e ksajgrup n t vrtet jan t gjeneruara n mnyr dinamikenga thirrjet funksion.Undo edits

  • 7/31/2019 csharp tutotial

    34/52

    Classes, Objects, and Methodsclass StackClass{

    string myString;private int [] stack_ref;private int max_len, top_index;public StackClass() { // A constructor

    stack_ref = new int [100];max_len = 99;

    top_index = -1;}public void push (int number) {

    if (top_index == max_len) Console.WriteLine("Error in push-stack is full");else stack_ref[++top_index] = number;

    }

    public void pop () {if (top_index == -1) Console.WriteLine("Error in push-stack is empty");else --top_index;

    }public int top () {return (stack_ref[top_index]);}public bool empty () {return (top_index == -1);}

    }

  • 7/31/2019 csharp tutotial

    35/52

    Classes, Objects, and Methodsclass StockExample

    {public static void Main (string[] args) {

    StackClass myStack = new StackClass();

    myStack.push(42);

    myStack.push(29);

    Console.WriteLine("29 is: {0}", myStack.top());

    myStack.pop();

    Console.WriteLine("42 is: {0}", myStack.top());myStack.pop();

    myStack.pop(); // Produces an error message

    }

    }

  • 7/31/2019 csharp tutotial

    36/52

    Delegates and Events Delegatt lloje t referencs t cilat lejojn thirrje indirekte pr

    metodat. Nj shembull i deleguari mban referenca n nj numr tmetodave, dhe duke thirrur me nj delegat shkakton t gjitha ktometoda q do t quhet.Dobia e delegatve qndron n faktin sefunksionet q Zelea ata jan t verbr me metodat baz. Ajo mundt shihet se delegatt jan funksionalisht dhe jo t ngjashme me C

    + + 's pointers funksion. Megjithat, sht e rndsishme tmbajm n mendje dy dallime kryesore. S pari, delegatt jan tllojeve t referencs se sa lloje t vler. S dyti, disa delegat tvetme mund t referohen metodave t shumta.Undo edits

  • 7/31/2019 csharp tutotial

    37/52

    Delegates and Events Delegatt mund t specifikohen m vete n nj hapsira,

    prndryshe mund t prcaktohet brenda nj klase tjetr.N do rast, deklarata prcakton nj klas t re, e cilatrashgon nga System.MulticastDelegate. Secili delegatsht i kufizuar n referenca metodat e nj lloji t veant

    vetm.Lloji tregohet nga deklarata delegatve -parametrat t dhna dhe llojin e kthimit t dhna ndeklaratn e delegatve duhet t ndahet nga metodat rastesaj delegat reference. Pr t ilustruar kt: nj delegatspecifikuar si m posht mund t prdoret pr t'iureferuar vetm pr metoda t cilat kan nj kontribut tvetme String dhe asnj vler e kthimit.

  • 7/31/2019 csharp tutotial

    38/52

    Delegates and Events public delegate void Print (String s);

    Suppose, for instance, that a class contains the followingmethod:

    public void realMethod (String myString) {

    // method code

    }

    Another method in this class could then instantiate the

    Print delegate in the following way, so that it holds areference to realMethod;

    Print delegateVariable = new Print(realMethod);

  • 7/31/2019 csharp tutotial

    39/52

    Delegates and Events Ne mund t vini re dy pika t rndsishme n lidhje me

    kt shembull. S pari, metoda e pakualifikuar kaluar nkonstruktor delegatve njihet n mnyr implicite si njmetod t shkalls s kalon at. Kjo sht, kodi sht ebarabart me: Printo Printo delegateVariable = Hapreja (this.realMethod); Ne mund, megjithat, n t njjtnmnyr t kaloj n konstruktor delegatve metodat eklass raste t tjera, apo edhe metodat statike t klass.N rastin e ish, shembull duhet t ekzistoj n kohnreferenc metod sht e kaluar. N rastin e fundit(ilustruar m posht), klas nuk duhet t jetinstantiated. Print delegateVariable = new PRINT(ExampleClass.exampleMethod);Undo edits

    l d

  • 7/31/2019 csharp tutotial

    40/52

    Delegates and Events The second thing to note about the example is that all

    delegates can be constructed in this fashion, to create adelegate instance which refers to a single method. However, as we noted before, some delegatestermed

    multicast delegatescan simultaneously referencemultiple methods. These delegates must - like our Print

    delegatespecify a void return type. The method invocation is termed an event, and the

    running of the method is the handling of the event. Antypical example of an event is a user's selection of a

    button on a graphical user interface; this action maytrigger a number of methods to handle it. The event keyword is used to declare a particular

    multicast delegate.

  • 7/31/2019 csharp tutotial

    41/52

    Delegatesusing System;

    using System.Threading;

    public class Ticker

    {

    private int i = 0;

    public void Tick(Object obj)

    {

    Console.WriteLine("tick " + ++i);

    }

    }

    public class DelegateExample

    {

    static void Main(string[] args)

    {

    Ticker ticker = new Ticker();TimerCallback tickDelegate = new TimerCallback(ticker.Tick);

    new Timer(tickDelegate, null, 0, 500);

    Thread.Sleep(5000); // The main thread will now sleep for 5 seconds:

    }

    }

    I /O

  • 7/31/2019 csharp tutotial

    42/52

    Input/Outputusing System;

    using System.IO;

    class DisplayFile

    {

    static void Main(string[] args)

    {

    StreamReader r = new StreamReader(args[0]);

    string line;

    Console.Write("Out File Name: ");

    StreamWriter w = new StreamWriter(Console.ReadLine());

    while((line = r.ReadLine()) != null) {

    Console.WriteLine(line);

    w.WriteLine(line);

    }

    r.Close();

    w.Close();

    }

    }

    E i

  • 7/31/2019 csharp tutotial

    43/52

    Exceptions Trajtimin prjashtim n C #, Java dhe sht mjaft e

    ngjashme. Megjithat, C # vijon C + + pr t lejuar qautori t injoroj m shum nga prjashtimet q mund tjet hedhur (nj prjashtim i cili sht hedhur, por nukkapet do t ndal programin dhe mund t hedhin nj kuti

    t dialogut). Pr t kapur nj lloji t veant prjashtimn nj pjes t kodit, ju duhet q s pari t prfundoj atn nj bllok provoni dhe pastaj specifikoni nj bllokcatch prputhen at lloj t prjashtim. Kur nj prjashtim

    ndodh n kodin brenda bllokut t provoni, ekzekutimiKodi lviz deri n fund t kutis s provoni dhe shikonpr nj mbajts prjashtim t prshtatshme.

  • 7/31/2019 csharp tutotial

    44/52

    E i

  • 7/31/2019 csharp tutotial

    45/52

    Exceptionsusing System;public class ExceptionDemo {

    public static void Main () {try {getException();

    } catch (Exception e) {

    Console.WriteLine("We got an exception");}finally {Console.WriteLine("The end of the program");

    }

    }public static void getException() {

    throw new Exception();}

    }

    U i h C# C il

  • 7/31/2019 csharp tutotial

    46/52

    Using the C# Compiler As we have noted earlier, C# classes are compiled in the

    first place to the Common Language RuntimeIntermediate Language (IL).

    csc file.cs (mcs file.cs in mono) Where the required classes are held in more than one file,

    these should be listed, separated by spaces, as in:csc file1.cs file2.cs

    Broadly speaking, one can compile C# classes into eitherexecutable files or dynamic link library - DLL - files withthe/t switch.

    Preprocessor directives tags included within classspecifications; they are used to give the compileradditional information about regions of code.

    C d D t ti

  • 7/31/2019 csharp tutotial

    47/52

    Code Documentation # C compiler mbshtet krijimin automatik t dokumentacionit t

    klass. Ku funksionaliteti ekuivalent pr Java prodhon HTML,dokumentuesi # C prodhon XML. Kjo do t thot se C #dokumentacioni nuk sht aq e menjher i gatshm pr tprdorur si dokumentacionit Java. Megjithat, kjo nuk lejon q tket aplikime t ndryshme t cilat mund t importojn dhe t

    prdorin dokumentacionin C # n mnyra t ndryshme. (Shnim:duke prdorur Visual Studio ju gjithashtu mund t krijojdokumentacionin HTML, por ne nuk do t mbulojn kt ktu). Tdokumentoj do element n nj skenar C #, ju paraprijnelementin me elemente XML. Secili prej linjave t prbr kt

    kod dokumentar duhet t shnohet off si komente duke prdorurtreguesin e mposhtme t veant Komenti (ju mund ta krahasonikt me treguesit Komento standarde).

    C d D t ti

  • 7/31/2019 csharp tutotial

    48/52

    Code Documentation Kodi vijim jep nj shembull se si mund t japin informacion

    rishikim pr nj klas. / / / / / / Klasa myClass

    prfaqson nj klas arbitrar / / / myClasspublik klas Gjenerimi C Dokumentimi msgstr Ju thoni prpiluespr t prodhuar dokumentacionin kur hartimin duke iu lutur me tkaloni: / doc: fotografi N kt kaloni, fotografi paraqet emrin eskedarit q doni t dokumentacionit me shkrim. Si dokumentacion

    sht gjeneruar n formatin XML, dosja duhet t ket extension.XML. Kshtu, pr shembull, pr t prodhuar dokumentacionin prnj program n sys.cs dosjes n nj skedar t quajtur my.xml, nedo t prdorim komandn: KSHC sys.cs / doc: my.xml

    S k t P i (TCP)

  • 7/31/2019 csharp tutotial

    49/52

    Socket Programming (TCP) # C API ofron streams TCP nga klasat e mposhtme:

    TcpListener - Kjo klas dgjon pr lidhje nga rrjeti klientt TCP.TcpClient - Kjo klas Ofron lidhjet klientit pr TCP shrbimevet rrjetit. Socket-zbaton ndrfaqe bazat Berkeley. TcpListener(IPAddress, Port): AcceptTcpClient - nj metod bllokimin qkthen nj TcpClient ju mund t prdorni pr t drguar dhe marr

    t dhna. Fillimi - Fillon dgjuar pr krkesat lidhje hyrse.AcceptSocket - nj metod bllokimin q kthen nj grop ju mundt prdorni pr t drguar dhe marr t dhna. Mbylle - mbylldgjues.

    S k t P i (TCP)

  • 7/31/2019 csharp tutotial

    50/52

    Socket Programming (TCP)

    TcpClient (hostname string, int port);:

    GetStream - kthen NetworkStream prdorur prt drguar dhe marr t dhna. Mbyll: Mbylllidhjen TCP dhe liron t gjitha burimet q lidhen

    me TcpClient. NetworkStream int Lexo (byte []tampon, int offset, int size) - lexon t dhna ngaNetworkStream. Shkruani (byte [] tampon, int

    offset, int size) - Shkruan dhna nNetworkStream. Mbylle - mbyllNetworkStream.Undo edits

    S k t P i (UDP)

  • 7/31/2019 csharp tutotial

    51/52

    Socket Programming (UDP) # C API ofron streams UDP nga klasat e mposhtme: UdpClient

    - Kjo klas Ofron User Datagram Protocol (UDP) shrbimet errjetit. Konstruktor UdpClient: publik UdpClient (familjaAddressFamily); UdpClient publike (int port); publik UdpClient(localEP IPEndPoint); UdpClient publike (int, port familjaAddressFamily); publik UdpClient (hostname string, int port);IPEndPoint: initializes nj shembull t ri t klass IPEndPoint.IPEndPoint publike (adresa e gjat, port int) IPEndPoint publike(IPAddress adresa, port int);

    S k t P i (UDP)

  • 7/31/2019 csharp tutotial

    52/52

    Socket Programming (UDP)

    UdpClient: byte publik [] Merre (remoteEP ref

    IPEndPoint): Kthen Datagram UDP q u shtdrguar nga nj host t largt. Drgo: Drgon njDatagram UDP n nj host t largt. int publik

    Send (byte [] dgram, n int bytes) Drgo intpublik (bajt [] dgram, bytes int, t endpointIPEndPoint); Drgo int publik (bajt [] dgram,

    bytes int, t hostname string, int port); Mbylllidhjen UDP.Undo edits