You are on page 1of 52

C# Tutorial

Orhan R Bakalli

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 Metodat Futja Polymorphism (Metodat e trashguara) Konstante, fusha, Prona dhe Indexers Delegatt dhe Ngjarje prjashtime Dokumentacioni Kodi

C# Tutorial

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 qenit e Nje Bote ne te ciln shume aplikacione drejtuar ne mnyr te shprndar npr internet. Ne ndjekse te identifikojn Nje numr te motiveve te ndryshme lvizse Kete Vizion. Programimi object-oriented Prpiluar Nje ktu Barbie te kandidoj Kudo. Shrbimi i orientuar drejt aplikimit. NET Fillon Microsoft JVM? . NET Ka qen e ndrtuar MBI teknologjit e Hapur Standardizimi si XML Barbie SOAP Barbie Fillon drejt standardeve Datlindja te Hapur ne Vend se tendenca e Microsoft tij te pronarit.Undo redaktimet

Introducing the Microsoft .NET Framework


N fund zhvillimin e vizionit sht NET NET Framework (Microsoft JDK?) Q prmban.:Gjuh e prbashkt,. NET Korniz Klast, dhe nivelit m t lart karakteristika si ASP.NET dhe WinForms pr zhvillimin e aplikacioneve desktop.Runtime Common Language (CLR) (Microsoft JRE?) Menaxhon zbatimin e kodit 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 t prdoret pr t manipuluar. NET klasa kuadr, dhe CLR do t mbshtes ato.

C#
Jo t gjitha gjuht e mbshtetur t prshtatet trsisht me kujdes n kuadrin. NET, por nj gjuh q sht e garantuar pr t prshtaten n mnyr t prkryer sht C #. C # (C Sharp), nj pasues t C + +, sht liruar n lidhje me kuadrin. NET. C dizajn Qllimet msgstr me: Jet t rehatshme pr C + + programues Fit pastr n. Runtime NET Gjuhsh e prbashkta CLR) Thjeshtoj C + modelin + E T siguroj sasi t drejtn e fleksibilitetit Komponent-centric mbshtetje t zhvillimitUndo edits

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, t cilat hequr disa prej detyrave t ult t mirmbajtjes t nivelit nga programues. 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 - me interpretimin ose thjesht-n-koh prpilimin - n nj makin t prshtatshme virtuale. N C #, megjithat, m sht dhn mbshtetje pr hartimin e mtejshm t kodit gjuhn ndrmjetme n kodin amtare. Ashtu si Java, C # i jep dor nga trashgimi klas t shumta n favor t nj modeli trashgimi t vetme. C # mbshtet trashgimi t shumta e interfaces.

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 t sigurta llojet me vler t cilat jan t kufizuara pr nj grup t definuar t variablave t vazhdueshme, dhe structs, t cilat jan prdorues t prcaktuara lloje vler. Java nuk ka enumerations, por mund t specifikoni nj klas t imitojn ato. Ndryshe nga Java, C # ka funksion t dobishme q ne mund t mbingarkoj operatorve t ndryshme. Megjithat, polymorphism sht trajtuar n nj mnyr m t komplikuar, me rregulla t nxjerra n klas ose thelbsore ose fshehur metoda super klass. N Java, multi-dimensionale vargjeve jan zbatuar vetm me nj-dimensionale vargjeve ku vargjeve mund t jen antar t vargjeve t tjera. Prve vargjeve t dhmbzuar, megjithat, C # edhe zbaton vargjeve t vrtet drejtkndshe.

C# versus C++ (Differences)


C # prdor delegat - lloj-pointers t sigurta metod. Kto jan prdorur pr t zbatuar ngjarje trajtimin-. Edhe pse ka disa elemente q rrjedhin nga Visual Basic dhe Java, C + + eshte C # 's relative afrt. N nj ndryshim t rndsishm nga C + +, C # Kodi nuk krkon fotografi titull. T gjitha Kodi sht shkruar Inline.. NET Runtime n t cilat C # drejton kryen menaxhimin e kujtess kujdeset pr detyrat si grumbullimin e mbeturinave. Pr shkak t ksaj, prdorimi i pointers n C # sht shum m pak e rndsishme se n C + +. Pointers mund t prdoret n C #, ku kodi sht shnuar si i pasigurt, por ato jan vetm t vrtet t dobishme n situata ku fitimet e performancs jan n nj fitim absolut. N prgjithsi, t gjitha llojet msgstr C rrjedh prfundimisht nga lloji i objektit.Undo edits

C# versus C++ (Differences)


Ka edhe dallime t veanta n mnyr q lloje t caktuara t prbashkta mund t prdoren. Pr shembull, C vargjeve msgstr jan kufijt kontrolluar ndryshe n C + +, dhe kjo nuk sht e mundshme, pra pr t shkruar e kaluara n fund t nj sr C #. C deklaratat msgstr jan mjaft t ngjashme me C + + pasqyra. T prmendet vetm nj shembull t nj ndryshim: Deklaratat e 'ndrprersin' ka ndryshuar n mnyr q sjellja 'bienprmes' nuk lejohet. Si u prmend m lart, C # jep deri n iden e trashgimis klass s shumfisht. Dallime t tjera q lidhen me prdorimin e klasave jan: nuk sht mbshtetje pr 'Properties' klasn e llojit t gjetur n Visual Basic, dhe metodat e klass jan quajtur prdorur. Operatori sesa :: operator.Undo edits

Getting Started Hello 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 .NET framework SDK) To run the program on Mono: mono HelloWorld.exe

Variable Types
C # sht nj lloj i sigurt-gjuha. Variablat jan deklaruar si t nj lloji t veant, dhe secili variabl sht e detyruar t mbaj vetm vlerat e llojit t saj t deklaruar. Variablat mund t mbaj as lloje vler ose llojet e referencs, apo ato mund t jen pointers. Nj variabl e llojeve me vler drejtprdrejt prmban vetm nj objekt me vler. Nj variabl e tipit reference direkt prmban nj referenc n nj objekt. Nj tjetr shum t ndryshueshme t prmbaj nj referenc pr t njjtin objekt. sht e mundur n C # pr t prcaktuar llojet e tuaja me vler duke deklaruar enumerations ose structs.

C# Pre-defined Value Types


C# Type .Net Framework Type Signed Bytes sbyte short int long byte ushort uint ulong float System.sbyte System.Int16 System.Int32 System.Int64 System.Byte System.Uint16 System.Uint32 System.Uint64 System.Single Yes Yes Yes Yes No No No No Yes 1 2 4 8 1 2 4 8 4 Possible Values -128 to 127 -32768 to 32767 231 to 231 - 1 263 to 263 - 1 0 to 255 0 to 65535 0 to 232 - 1 0 to 264 - 1
1.5 x 10-45 to 3.4 x 1038 with 7 significant figures 5.0 x 10-324 to 1.7 x 10308 with 15 or 16 significant figures 1.0 x 10-28 to 7.9 x 1028 with 28 or 29 significant figures

double
decimal char bool

System.Double
System.Decimal System.Char System.Boolean

Yes
Yes N/A N/A

8
12 2 1/2

Any Unicode character true or false

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 deleguar deklaratat objekt. Objekti x = objekt i ri (); x.myValue = 10; Ikni sekuenca dhe 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 t kthyer 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

Pointers
Nj tregues sht nj ndryshore q mban adresn e kujtess s nj lloji tjetr. N C #, pointers mund t deklarohet pr t mbajtur adresat e memories t llojeve t 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 i kufizuar pr kodin i cili sht shnuar si i pasigurt (hyrje kujtess).Undo edits

Pr t adresuar problemin e grumbullimit t mbeturinave, mund t deklaroj nj tregues brenda nj shprehje t caktuar. do lloje t vlers s deklaruar brenda kodit t pasigurt jan fikse automatikisht, dhe do t gjeneroj prpilojn me koh gabime n qoft se prdoren brenda shprehjeve fikse. E njjta gj nuk sht e vrtet pr lloje t referencs. Edhe pse zakonisht pointers mund t prdoren vetm me lloje t vler, nj prjashtim nga kjo prfshin vargjeve. Nj tregues mund t deklarohet n lidhje me nj grup, si n vijim: int [] = {a 4, 5}; int * b = a; far ndodh n kt rast sht se vendndodhja e kujtess mban b sht vend i llojit t par t mbajtur nga nj.

Pointers

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}};

A jagged 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}};

Enumerations
Nj regjistrimit sht nj lloj i veant i llojit t vlers s kufizuar n nj grup t kufizuar dhe t pandryshueshme t vlerave numerike. Kur ne t prcaktoj nj numrimit q ne ofrojm literals t cilat jan prdorur m pas si kosntanta pr vlerat e tyre prkatse.Kodi i mposhtm tregon nj shembull t till nj prkufizim: 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 kto dy rregulla: Pr literal i par: nse ajo sht e unassigned, pr t prcaktuar vlern e saj n 0. Pr do literal tjetr: nse ajo sht e unassigned, pastaj vendoset vlern e saj n nj m t madhe se vlera e literal msiprm.

Enumerations
using 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")); } }

Console.WriteLine("Number {1} of EnumTest.DAYS is {0}", day, day.ToString("d"))

Enumerations

is equivalent to:
Console.WriteLine(String.Format("Number {1} of EnumTest.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 as parameters, and slots them into the appropriate places within the format string it is passed. So this line of code is basically equivalent to:
Console.WriteLine("Number " + day.ToString("d").ToString() + " of EnumTest.DAYS is " + day.ToString());

The ToString method can take a single IFormatProvider parameter which indicates how the string conversion should be conducted. Values for this parameter can include things like g, d, x, f, etc.

Operators
C# has a number of standard operators, taken from C, C++ and Java. Most of these should be quite familiar to programmers. To overload an operator in a class, one defines a method using the operator keyword. For instance, the following code 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 operators should be overwritten if any one is.

Jump and Selection Statements


Deklarata pushim shprthen nga koh dhe pr sythe.Deklarata vazhdojn mund t vendoset n do struktur loop.Deklarata goto sht prdorur pr t br nj krcim n nj pjes t veant emrtuar t kodit t programit. Nse-tjetr deklaratat jan prdorur pr t kandiduar blloqe t kodit t kushtzuar me nj shprehje boolean vlersues t vrtet. Deklaratat Switch ofrojn nj mnyr t pastr e t shkruarit t shumta, nse deklaratat tjetr.Undo edits

Loop Statements
while loops while (expression) statement[s] do-while loops do statement[s] while (expression) for loops for (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);

Classes and Structs


Klasat siguroj templates nga e cila objekte - shembuj t ktyre klasave, mund t gjenerohet. Nj klas e specifikon nj tip dhe elementeve konstituive (antart tipit) t atij lloji. Nj klas mund t specifikoni dy lloje kryesore t antarve t tipit: Nj klas mund t saktsoj llojet e tjera - si vler dhe referenc. Llojet mund t prmbaj lloje tjera, q sht i njohur si frenimin, ose tjetr t bashkimit. Nj klas mund t specifikoj metodat - funksionet e projektuar pr leximin dhe manipulimin e vlers dhe llojet e referencs nj shembull prmban. C klasa msgstr mund t trashgojn nga nj klas baz t vetme ose nga ndonj numr t interfaces.

Namespaces
Namespaces can be thought of as collections of classes; they provide unique identifiers for types by placing them in an hierarchical structure. To use the System.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 } } }

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. The following is an example of a class declaration:
public class Shape { // class-body }

Attributes can be posted at the front of a class declaration. These comprise user-defined meta-data about the class; information which can be brought out at runtime.

Class Declaration
Ka shtat t ndryshme - optional - modifiers klass. Katr nga kto - publik, t brendshm, t mbrojtur, dhe private - jan prdorur pr t prcaktoj nivelet e aksesit t llojeve t prcaktuara nga klasat.Fjalen publik identifikon nj lloj si plotsisht t arritshme pr t gjitha llojet e tjera. Nse nj klas sht deklaruar si t brendshme, tip ajo definon sht i arritshm vetm pr llojeve brenda kuvendit njjtin nj vet-prmbante 'njsi e paketimit' kodi prmban, metadata etj.) Nse nj klas sht shpallur e mbrojtur, llojin e saj sht e arritshme nga nj lloj q prmbajn dhe do lloji q trashgon nga ky lloj prmban. Kur nj klas sht deklaruar si private, qasja n llojin ajo definon sht i kufizuar n nj lloj q prmban vetm.

Class Declaration
Lejet e lejuara nga brendshme t mbrojtura jan ato t lejuara nga niveli i mbrojtur plus ato t lejuara nga niveli i brendshm.Fjalen e re mund t prdoret pr klasat e mbivendosur. Nj klas deklarohen si abstrakte nuk mund vet t instanced - ajo sht projektuar vetm pr t qen nj klas baz pr trashgim. Nj klas e shpallur si t mbyllur nuk mund t trashgohet nga.Undo edits

Class Declaration
Baza klas pjes e deklarats klass specifikon emrin e klass dhe t gjitha klasa q ai trashgon nga.Linja m posht deklaron nj klas publik t quajtur DrawingRectangle q trashgon nga drejtkndsh klass baz dhe vizatim ndrfaqes: DrawingRectangle publik klas: Rectangle, Vizatim Interfaces jan deklaruar n t njjtn mnyr si klasa standarde, prve se ata prdorin ndrfaqe fjalen n vend t klass fjalen. Pr shembull: Vizatim publik ndrfaqe

Methods
Metodat jan operacione q lidhen me llojet. int shuma = Arithmetic.addTwoIntegers (4, 7); Nj deklarat e metod, t specifikuara n nj deklarat t klass, prbn nj metod kok-dhe nj metodtrup.Metoda e-kreu sht i prbr nga elementet e mposhtme (kllapa katrore fus ato t cilat jan opsionale). [atribute] [metod t modifiers] kthimit-lloj metoda-name ([formal-parametr-list]) Atributet Metoda t punoj n nj mnyr t ngjashme me ato t klasave.

Methods
Ka dhjet modifiers metod q mund t prdoren. Katr nga kto jan modifiers qasje q mund t prdoren n deklaratat e klass. Kto pun katr analoge pr mnyrn se si ata punojn n deklaratat e klass. T tjert jan si m posht: Abstract: Nj metod pa specifikuar trupin e saj. Metoda t tilla jan vet quajtur abstrakte. Nj klas prmban nj metod abstrakt ai nuk mund t instantiated.Modifier statike deklaron nj metod t jet nj metod klas (nj metod q mund t prdoret pa nj shembull). Hapsira t meta Paketat n Java) mund t mendohet si koleksionet e klasave, ata japin identifikues unik pr lloje duke i vendosur ato n nj struktur hierarkike.Undo edits

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 t dyja fshehur dhe mbizotruese. Overwriting metod e bn prdorimin e mposhtme tri metoda me kok fjal kye: ri, virtual, refuzo Dallimi kryesor n mes t fshehur dhe thelbsor ka t bj me zgjedhjen e cila metod pr t thirrur, ku klasa e deklaruar e nj ndryshore sht e ndryshme n klas drejtuar me koh t objektit ajo referencat.Undo edits

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, t brendshm 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 t jet nj fush e till n klas, pavarsisht nga numri i rasteve t klass. Readonly: Kur nj fush sht Readonly, vlera e tij mund t vendosen vetm nj her.

Constants, Fields, Properties and Indexers


Konstantet jan t llojeve t pandryshueshme, t shoqruara me klasa, t cilat jan t qasshme n kohn e kompilimit. Pr shkak t ktij fakti t fundit, konstanta mund t jet vetm lloje vler sesa llojet e referencs. publik const int Zona e = 4; Prona t paluajtshme mund t mendohet si fusha virtuale. Nga jasht, pron e nj klasa! Duket vetm si nj fush. Por nga brenda, prona sht prodhuar duke prdorur fushat aktuale t klass. Nse pronat jan fusha virtuale, indexers jan m shum si vargjeve virtuale. Ato lejojn nj klas t matem nj koleksion, ku elementt e ksaj grup n t vrtet jan t gjeneruara n mnyr dinamike nga thirrjet funksion.Undo edits

Classes, Objects, and Methods


class 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);} }

Classes, Objects, and Methods


class 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 } }

Delegates and Events


Delegatt lloje t referencs t cilat lejojn thirrje indirekte pr metodat. Nj shembull i deleguari mban referenca n nj numr t metodave, dhe duke thirrur me nj delegat shkakton t gjitha kto metoda q do t quhet.Dobia e delegatve qndron n faktin se funksionet q Zelea ata jan t verbr me metodat baz. Ajo mund t shihet se delegatt jan funksionalisht dhe jo t ngjashme me C + + 's pointers funksion. Megjithat, sht e rndsishme t mbajm n mendje dy dallime kryesore. S pari, delegatt jan t llojeve t referencs se sa lloje t vler. S dyti, disa delegat t vetme mund t referohen metodave t shumta.Undo edits

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 cila trashgon nga System.MulticastDelegate. Secili delegat sht 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 n deklaratn e delegatve duhet t ndahet nga metodat raste saj delegat reference. Pr t ilustruar kt: nj delegat specifikuar si m posht mund t prdoret pr t'iu referuar vetm pr metoda t cilat kan nj kontribut t vetme String dhe asnj vler e kthimit.

Delegates and Events


public delegate void Print (String s); Suppose, for instance, that a class contains the following method: 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 a reference to realMethod; Print delegateVariable = new Print(realMethod);

Delegates and Events


Ne mund t vini re dy pika t rndsishme n lidhje me kt shembull. S pari, metoda e pakualifikuar kaluar n konstruktor delegatve njihet n mnyr implicite si nj metod t shkalls s kalon at. Kjo sht, kodi sht e barabart me: Printo Printo delegateVariable = Hap reja (this.realMethod); Ne mund, megjithat, n t njjtn mnyr t kaloj n konstruktor delegatve metodat e klass raste t tjera, apo edhe metodat statike t klass. N rastin e ish, shembull duhet t ekzistoj n kohn referenc metod sht e kaluar. N rastin e fundit (ilustruar m posht), klas nuk duhet t jet instantiated. Print delegateVariable = new PRINT (ExampleClass.exampleMethod);Undo edits

Delegates and Events


The second thing to note about the example is that all delegates can be constructed in this fashion, to create a delegate instance which refers to a single method. However, as we noted before, some delegates termed multicast delegates can simultaneously reference multiple methods. These delegates must - like our Print delegate specify a void return type. The method invocation is termed an event, and the running of the method is the handling of the event. An typical example of an event is a user's selection of a button on a graphical user interface; this action may trigger a number of methods to handle it. The event keyword is used to declare a particular multicast delegate.

Delegates
using 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: } }

Input/Output
using 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(); } }

Exceptions
Trajtimin prjashtim n C #, Java dhe sht mjaft e ngjashme. Megjithat, C # vijon C + + pr t lejuar q autori t injoroj m shum nga prjashtimet q mund t jet hedhur (nj prjashtim i cili sht hedhur, por nuk kapet do t ndal programin dhe mund t hedhin nj kuti t dialogut). Pr t kapur nj lloji t veant prjashtim n nj pjes t kodit, ju duhet q s pari t prfundoj at n nj bllok provoni dhe pastaj specifikoni nj bllok catch prputhen at lloj t prjashtim. Kur nj prjashtim ndodh n kodin brenda bllokut t provoni, ekzekutimi Kodi lviz deri n fund t kutis s provoni dhe shikon pr nj mbajts prjashtim t prshtatshme.

Exceptions
For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero:
try { res = (num / 0); catch (System.DivideByZeroException e) { Console.WriteLine("Error: an attempt to divide by zero"); } }

You can specify multiple catch blocks (following each other), to catch different types of exception. A program can throw exceptions - including customized exceptions.

Exceptions
using 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(); } }

Using the C# Compiler


As we have noted earlier, C# classes are compiled in the first place to the Common Language Runtime Intermediate 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 either executable files or dynamic link library - DLL - files with the /t switch. Preprocessor directives tags included within class specifications; they are used to give the compiler additional information about regions of code.

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 t prdorur si dokumentacionit Java. Megjithat, kjo nuk lejon q t ket 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 krijoj dokumentacionin HTML, por ne nuk do t mbulojn kt ktu). T dokumentoj do element n nj skenar C #, ju paraprijn elementin me elemente XML. Secili prej linjave t prbr kt kod dokumentar duhet t shnohet off si komente duke prdorur treguesin e mposhtme t veant Komenti (ju mund ta krahasoni kt me treguesit Komento standarde).

Code Documentation
Kodi vijim jep nj shembull se si mund t japin informacion rishikim pr nj klas. / / / <summary> / / / Klasa myClass prfaqson nj klas arbitrar / / / </ Prmbledhje> myClass publik klas Gjenerimi C Dokumentimi msgstr Ju thoni prpilues pr t prodhuar dokumentacionin kur hartimin duke iu lutur me t kaloni: / doc: fotografi N kt kaloni, fotografi paraqet emrin e skedarit 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 pr nj program n sys.cs dosjes n nj skedar t quajtur my.xml, ne do t prdorim komandn: KSHC sys.cs / doc: my.xml

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 shrbimeve t rrjetit. Socket-zbaton ndrfaqe bazat Berkeley. TcpListener (IPAddress, Port): AcceptTcpClient - nj metod bllokimin q kthen 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 mund t prdorni pr t drguar dhe marr t dhna. Mbylle - mbyll dgjues.

Socket Programming (TCP)


TcpClient (hostname string, int port);: GetStream - kthen NetworkStream prdorur pr t drguar dhe marr t dhna. Mbyll: Mbyll lidhjen TCP dhe liron t gjitha burimet q lidhen me TcpClient. NetworkStream int Lexo (byte [] tampon, int offset, int size) - lexon t dhna nga NetworkStream. Shkruani (byte [] tampon, int offset, int size) - Shkruan dhna n NetworkStream. Mbylle - mbyll NetworkStream.Undo edits

Socket Programming (UDP)


# C API ofron streams UDP nga klasat e mposhtme: UdpClient - Kjo klas Ofron User Datagram Protocol (UDP) shrbimet e rrjetit. Konstruktor UdpClient: publik UdpClient (familja AddressFamily); UdpClient publike (int port); publik UdpClient (localEP IPEndPoint); UdpClient publike (int, port familja AddressFamily); 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);

Socket Programming (UDP)


UdpClient: byte publik [] Merre (remoteEP ref IPEndPoint): Kthen Datagram UDP q u sht drguar nga nj host t largt. Drgo: Drgon nj Datagram UDP n nj host t largt. int publik Send (byte [] dgram, n int bytes) Drgo int publik (bajt [] dgram, bytes int, t endpoint IPEndPoint); Drgo int publik (bajt [] dgram, bytes int, t hostname string, int port); Mbyll lidhjen UDP.Undo edits

You might also like