334
yvela ufleba daculia all rights reserved jemal anTiZe daprogrameba C# enaze leqciebis kursi Tbilisi 2011

C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

yvela ufleba daculia

all rights reserved

jemal anTiZe

daprogrameba C# enaze

leqciebis kursi

Tbilisi 2011

Page 2: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

2

ს ა რ ჩ ე ვ ი

1 ლექცია მუშაობის დაწყება c#-ში . . . . . . . . . . . . . 5

2 ლექცია ცვლადები, ტიპები და ოპერატორები . . . . . . . . 10

3 ლექცია პროგრამის მართვის ინსტრუქციები . . . . . . . . 23

4 ლექცია ციკლის ინსტრუქციები . . . . . . . . . . . . . 31

5 ლექცია მეთოდები . . . . . . . . . . . . . . . . . . . 38

6 ლექცია სახელთა არეები . . . . . . . . . . . . . . . . 46

7 ლექცია კლასები . . . . . . . . . . . . . . . . . . . 52

8 ლექცია მემკვიდრეობითობა . . . . . . . . . . . . . . 56

9 ლექცია პოლიმორფიზმი . . . . . . . . . . . . . . . 61

10 ლექცია თვისებები . . . . . . . . . . . . . . . . . . 65

11 ლექცია მაინდექსირებლები . . . . . . . . . . . . . . 76

12 ლექცია სტრუქტურები . . . . . . . . . . . . . . . . 83

13 ლექცია ინტერფეისები . . . . . . . . . . . . . . . . . 93

14 ლექცია დელეგატები და ხდომილებები . . . . . . . . . 96

15 ლექცია განსაკუთრებულ შემთხვევათა დამუშავება . . . . 104

16 ლექცია ატრიბუტების გამოყენება . . . . . . . . . . . . 109

17 ლექცია გადანომრვა . . . . . . . . . . , . . . . . . 114

18 ლექცია ოპერატორების გადატვირთვა . . . . . . . . . 123

Page 3: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

3

19 ლექცია ჩადგმა (ინკაფსულაცია) . . . . . . . . . . . . 128

20 ლექცია ძირითადი კოლექციები . . . . . . . . . . . . 135

21 ლექცია ანონიმური მეთოდები . . . . . . . . . . . . . 140

22 ლექცია c#-ის ტიპების შესახებ . . . . . . . . . . . . . 143

23 ლექცია null ტიპის გამოყენება . . . . . . . . . . . . . 149

მაგალითები . . . . . . . . . . . . . . . . . . . . . . . 151

ფაილის შექმნა და წაკითხვა . . . . . . . . . . . . . . . . . 151

მასივის გამოყენება . . . . . . . . . . . . . . . . . . . . . 152

ატრიბუტების გამოყენება . . . . . . . . . . . . . . . . . 153

ტოკენების გამოცნობა . . . . . . . . . . . . . . . . . . . 160

სტრუქტურის გამოყენება . . . . . . . . . . . . . . . . . . 164

თვისებების გამოყენება . . . . . . . . . . . . . . . . . . . 165

მაინდექსირებლის გამოყენება . . . . . . . . . . . . . . . . 168

delegatebis gamoyeneba . . . . . . . . . . . . . . . . . 172

ველები . . . . . . . . . . . . . . . . . . . . . . . . . . 178

გარდაქმნები . . . . . . . . . . . . . . . . . . . . . . . 181

ოპერატორების გადატვირთვა . . . . . . . . . . . . . . . 187

ნულ ტიპები . . . . . . . . . . . . . .. . . . . . . . . . 195

ბიბლიოთეკები . . . . . . . . . . . . . . . . . . . . . . 201

ცხადი ინტერფეისი . . . . . . . . . . . . . . . . . . . . . 205

Page 4: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

4

ხდომილებები . . . . . . . . . . . . . . . . . . . . . . . 210

ბრძანებათა სტრიქონი . . . . . . . . . . . . . . . . . . . 218

კოლექციები . . . . . . . . . . . . . . . . . . . . . . . . 220

პირობითი მეთოდები . . . . . . . . . . . . . . . . . . . . 227

ვერსიები . . . . . . . . . . . . . . . . . . . . . . . . . . 238

დაუცველი . . . . . . . . . . . . . . . . . . . . . . . . . . 240

ძაფები . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

უსაფრთხოება . . . . . . . . . . . . . . . . . . . . . . . . . 267

Pinvoke . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

კერძო ტიპები . . . . . . . . . . . . . . . . . . . . . . . . 288

Oledb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293

ინდექსირებული თვისებები . . . . . . . . . . . . . . . . . 297

Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306

Cominternop2 . . . . . . . . . . . . . . . . . . . . . . . . . 315

Cominternop1 . . . . . . . . . . . . . . . . . . . . . . . . . . 316

ანონიმური დელეგატები . . . . . . . . . . . . . . . . . . . . 326

ინგლისურ-ქართული ტერმინოლოგიური ლექსიკონი . . . . . . . 331

Page 5: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

5

1 leqcia

muSaobis dawyeba C#-Si

Sinaarsi :

programis ZiriTadi struqtura;

namespace-is gamoyeneba;

Main meTodis gamoyeneba;

Setana comand line-iT;

programis zogadi struqtura

martivi C# programa

// Namespace-is gamocxadeba

using System;

// programis dawyebis klasi

class Cmisalmeba

{

// Main meTodi iwyebs programis Sesrulebas

static void Main()

{

// ekranze gamotana

Console.WriteLine("viwyebT C# Seswavlas!");

}

}

Page 6: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

6

am programis kompilacia SeiZleba Semdegi brZanebiT(igulisxmeba, rom

programis teqsti Cawerilia Cmisalmeba.cs failSi):

csc.exe Cmisalmeba.cs

kompilaciis Sedegi Caiwereba failSi Cmisalmeba.exe standartul

direqtoriaSi. Tu sxvagan gvinda Cawera, maSin unda mivuTiToT sruli gza.

//-iT iwyeba erTstriqoniani komentari. igi kompilaciis dros ar

ganixileba da gamoiyeneba mxolod rogorc programis axsna-gamarteba.

brZanebaTa striqoni aris fanjara, romlis saSualebiTac SeiZleba

brZanebebisa da programebis gaSveba saTanado teqstis akrefiT. rom

gamoviyenoT brZanebaTa striqonSi muSaoba saWiroa, magaliTad, WINDOWS

XP operaciul sistemaSi SevideT START meniuSi avirCioT RUN da avkrifoT

CMD. SevniSnoT, rom C# klaviaturis registrisadmi grZnobiarea -

ansxvavebs did da patara asoebs.

Namespace-is gamocxadeba using System niSnavs, rom Tqven SegiZliaT

isargebloT System-Si moTavsebuli meTodebis klasebiT ise, rom win ar

miuweroT saxeli System maSin, roca am gamocxadebis gareSe unda miuTiToT

sruli saxeli. magaliTad, wina programaSi gamoyenebulia meTodi

Console.WriteLine System-is win miweris gareSe, radgan programaSi

gamoyenebulia using System. programaSi Semotanilia klasi saxeliT

Cmisalmeba, romelic Seicavs Main meTods da igi aris programaSi

Sesasvleli wertili, saidanac iwyeba programis Sesruleba. yovel

programas unda hqondes Main meTodi, romelic moTavsebulia ZiriTad

klasSi. klasisa da meTodis sazRvrebi ganisazRvreba gaxsnili da

daxuruli figuruli frCxilebiT. specifikacia void miuTiTebs, rom meTods

ar gamoaqvs raime mniSvneloba. Main meTods yovelTvis aqvs void

specifikacia. am magaliTSi Main meTods aqvs erTaderTi instruqcia,

romelic aris System-is Console jgufis meTodi WriteLine. mas gamoaqvs teqsti

ekranze da gadadis axal striqonze. Console aris Namespace-is klasi da

WriteLine aris misi meTodi. klasebsa da Namespace dawvrilebiT SeviswavliT

Semdeg leqciebSi. isini aq motanili arian programis struqturis

saCveneblad. static modifikatori miuTiTebs, rom am meTodis gamoiyeneba

SeiZleba mxolod am klasSi.

Page 7: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

7

brZanebaTa striqoniT Setana

brZanebaTa striqoniT Cven SegviZlia gavxsnaT zogadi moxmarebis

programebi da vimuSaoT masSi. magaliTad,

Notepad.exe saxeli.txt

es brZaneba gamoiZaxebs Notepad redaqtors da masSi gaxsnis saxeli.txt fails.

rasakvirvelia Tu igi arsebobs im direqtoriebSi, romlebsac sistema

icnobs. Cven SegviZlia brZanebaTa striqoniT SevitanoT argumentebi da

gamoviyenoT isini programaSi. Tu rogor gavakeToT es, amisaTvis

ganvixiloT magaliTi:

// Namespace-is gamocxadeba

using System;

// programis dawyebis klasi

class Csaxeli1

{

//Main iwyebs programis gamoTvlas.

static void Main(string[] args)

{

// ekranze gamotana

Console.WriteLine("salami, {0}!", args[0]);

Console.WriteLine("gisurvebT warmatebas!");

}

}

Page 8: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

8

Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args

aris string tipis masivi. misi mniSvnelobebi aiReba brZanebaTa striqonidan.

sadac pirveli saxeli aris programis failis saxeli da danarCeni

saxelebi arian args masivis elementebi. masivis elementebis gadanomvra

iwyeba nulidan.

Console.WriteLine("salami, {0}!", args[0]) instruqcia

iRebs brZanebaTa striqonidan programis saxelis Semdeg saxels da mas

ganixilavs rogorc args[0]-is mniSvnelobas. Tu es saxelia “petre”, maSin

programa gamoitans ekranze

salami, petre!

gisurvebT warmatebas!

dialogi brZanebaTa striqonis saSualebiT

programaSi striqonis Setanis meore xerxia misi Setana Console-s

saSualebiT. ganvixiloT programa:

// Namespace-is gamocxadeba

using System;

// programis dasawyisis klasi

class Csaxeli2

{

//Main iwyebs programis Sesrulebas.

public static void Main()

{

// Setana Console-s saSualebiT

// cvladis gansazRvra

Console.Write("სალამი, {0}! ", Console.ReadLine());

Page 9: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

9

Console.WriteLine("გისურვებთ წარმატებას!");

}

}

Console.Write axdens Tavisi argumentis gamotanas ise, rom ar gadadis axal

striqonze. Console.ReadLine() elodeba momxmareblisagan striqonis Setanas

klaviaturidan. momxmarebelma unda akrifos striqoni da daaWiros xeli

ENTER-s. amis Semdeg, {0}-is nacvlad aiReba akrefili striqoni da

Console.WriteLine gamoitans miRebul striqons. Console.Write("სალამი, {0}! ",

Console.ReadLine()); SeiZleba Seicvalos instruqciebiT

string name=Console.ReadLine ;

Console.Write("salami, {0}! ",name);

Sedegad gamoitaneba ekranze igive. aseT reJimSi programis gamotanasa da

momxmareblis muSaobas aqvs Semdegi saxe:

ekranze gamoitaneba - Tqveni saxeli? akrifeT Tqveni saxeli klaviaturaze

da daaWireT ENTER klaviSas. amis Semdeg ekranze gamoitaneba

salami, <Tqvens mier akrefili saxeli>! gisurvebT warmatebas !

amgvarad, Cven SeviswavleT Tu rogoria programis struqtura C#-Si,

muSaoba brZanebaTa striqonis gamoyenebiT da rogor gamoviyenoT

brZanebaTa striqonis argumentebi programaSi.

Page 10: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

10

2 leqcia

cvladebi, tipebi da operatorebi

cvladi gamoiyeneba programaSi mniSvnelobaze misaTiTeblad. cvladis

gamocxadeba niSnavs cvladisTvis saxelisa da tipis gansazRvras, xolo

cvladis gansazRvra aris misTvis mniSvnelobis micema. meorenairad mas

cvladis inicializacias uwodeben. amave dros ganisazRvreba adgili,

sadac es mniSvneloba iwereba. gamoyofili adgilis sigrZe ganisazRvreba

cvladis tipis mixedviT, xolo programaSi misi gamoyenebis are

ganisazRvreba cvladis gamocxadebis adgiliT. tipi aris mniSvnelobaTa

fiqsirebuli simravle, saidanac mniSvneloba aiReba. arseboben ori saxis

tipebi: daprogramebis enaSi dafiqsirebuli tipebi, meorenairad maT

Cadgmul an martiv tipebs uwodeben da programistis mier Sedgenili

tipebi, romlebic miiRebian martivi tipebis kombinaciiT. C#-Si martivi

tipebia: bulis, integraluri, namdvili da striqonuli tipebi. ganvixiloT

TiToeuli cal-calke.

bulis tipi. es simravle Sedgeba ori mniSvnelobisagan: WeSmariti da

mcdari. WeSmariti mniSvneloba aRiniSneba true-Ti, xolo mcdari

mniSvneloba false-Ti. maT ewodebaT bulis(logikuri) konstantebi. isini

gamoiyenebian logikuri gamosaxulebis WeSmaritebis dasadgenad. Tu ra

aris logikuri gamosaxuleba da rogor unda gamoviyenoT igi SeviswavliT

mogvianebiT.

integraluri tipi. C#-Si integralur tips miekuTvneba mTeli ricxvebi

niSniT an uniSnod da char tipis simboloebi, romlebic warmoadgenen

Unicode-is simboloebs(ixileT internetSi Unicode cxrili). ganvixiloT

cxrili, sadac mocemulia integral tipis qvetipebi, mexsierebaSi maTTvis

gamoyofili bitebis raodenoba da im ricxvebis diapazoni, romlebic

SeiZleba warmoidginos mocemuli qvetipiT.

qvetipi sigrZe bitebSi diapazoni

sbyte 8 -128-dan 127-mde

Page 11: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

11

byte 8 0-dan 255-mde

short 16 -32768-dan 32767-mde

ushort 16 0-dan 65535-mde

int 32 -2147483648-dan 2147483647-mde

uint 32 0-dan 4294967295-mde

long 64 -92233720 36854775808-dan 9223372036854775807-mde

ulong 64 0-dan 18446744073709551615-mde

char 16 0-dan 65535-mde

magaliTad, sbyte tipis cvlads mexsierebaSi gamoeyofa 8 bitis sigrZis

adgili. mas SeiZleba hqondes nebismieri mniSvneloba -128-dan 127-is

CaTvliT.

namdvili tipi. namdvili tipis ricxvebs miekuTvnebian namdvili ricxvebi

moZravi wertiliT, namdvili ricxvebi moZravi wertiliTa da ormagi

sizustiT da aTwiladi ricxvebi. ganvixiloT cxrili:

tipi sigrZe bitebSi sizuste diapazoni

float 32 7 aTobiTi cifri 1.5 x 10-45

-dan 3.4 x 1038

double 64 15-16 aTobiTi cifri 5.0 x 10-324

t-dan 1.7 x 10308

decimal 128 28-29 aTobiTi cifri 1.0 x 10-28

–dan 7.9 x 1028

am cxrilSi, diapazoni zustad gviCvenebs Tu rogori ricxvebi ekuTvnian

konkretul tips. namdvili ricxvebi moZravi wertiliT Sedgeba

Page 12: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

12

nawilebisagan: mTeli, romelsac mosdevs wertili, Semdeg aTwiladi nawili

da Semdeg aTi xarisxad mTeli. zogadad igi Caiwereba ase: n.m10p sadac n

da p mTeli ricxvebia, m naturaluri ricxvia. aTwiladi ricxvi Caiwereba

n.m saxiT. n SeiZleba ar gvqondes.

striqonuli tipi. striqonuli tipis konstanta warmoidgineba ormag

brWyalebSi moTavsebuli simboloebiT, sadac simboloebi ekuTvnian ASCII

standarts. zogierTi maTgani arian arabeWdvadi simboloebi. isini

warmoidginebian striqonSi zogierTi beWdvadi simboloebiT, romelTac win

miwerili aqvT simbolo “daxrili xazi”(\). aseT simboloebs ewodebaT

specialuri simboloebi. magaliTad, \n aris specialuri simbolo, romelic

aRniSnavs axal striqonze gadasvlas. specialuri simboloebi mocemulia

Semdeg cxrilSi:

specialuri simbolo mniSvneloba

\' erTmagi brWyalebi

\" ormagi brWyalebi

\\ daxrili xazi

\0 nul-kodi

\a zari

\b daxrili xazii

\f formis CatvirTva

\n axal striqonze gadasvla

\r karetis ukan dabruneba

\t horizontaluri tabulacia

\v vertikaluri tabulacia

Page 13: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

13

garda amisa, C#-Si arsebobs striqonebis specialuri warmodgena, roca

striqons win ewereba simbolo @ . aseT SemTxvevaSi striqonis SigniT

daxrili xazi gamoiyeneba Cveulebrivi azriT, rac striqons advilad

wasakiTxs xdis. magaliTad, aviRoT raime gza failebis sistemaSi

c:\a\b\magaliti.txt striqonSi igi Caiwereba ase: “c:\\a\\b\\magaliti.txt”, xolo

specialuri CaweriT @”c:\a\b\magaliti.txt”.

operatorebi. operatorebi gamoiyenebian gamosaxulebis Sesadgenad. C#-Si

ansxvaveben pirvelad, erTadgilian da oradgilian operatorebs

imisdamixedviT Tu ramden operands iyenebs operatori. gamosaxulebaSi rom

ganvsazRvroT oradgiliani operatorebis Sesrulebis rigi, amisaTvis

gamoiyeneba operatoris prioriteti da asociaturoba. gamosaxulebidan

aRebuli ori mezobeli operatoridan is sruldeba pirvelad, romelsac

ufro maRali prioriteti aqvs, xolo toli prioritetebis SemTxvevaSi

ganixileba asociaturoba. Tu operatori marcxniv asociaturia, maSin

sruldeba marcxena operatori, xolo Tu operatori marjvniv asociaturia,

maSin sruldeba marjvena operatori. Tu Cven gvinda ori mezobeli

operatoridan romelime Sesruldes pirvelad, maSin mas vsvamT Tavisi

operandebianad mrgval frCxilebSi. pirveladi da erTadgiliani

operatorebi sruldebian marcxnidan marjvniv rigis mixedviT.

qvemoT mocemulia cxrili, sadac CamoTvlilia operatorTa

kategoriebi maT prioritetTa klebis mixedviT da mocemulia, agreTve, maTi

asociaturoba.

kategoria prioritetis

mixedviT operatorebi asociaturoba

pirveladi x.y f(x) a[x] x++ x-- new typeof default

checked unchecked delegate marcxniv

Page 14: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

14

erTadgiliani + - ! ~ ++x --x (T)x marcxniv

multiplikaturi * / % marcxniv

aditiuri + - marcxniv

Zvris << >> marcxniv

relaciuri < > <= >= is as marcxniv

tolobis = != marjvniv

logikuri da & marcxniv

logikuri XOR ^ marcxniv

logikuri an | marcxniv

pirobiTi da && marcxniv

pirobiTi an || marcxniv

nul kodi ?? marcxniv

ternaluri ?: marjvniv

miniWebis = *= /= %= += -= <<= >>= &= ^= |=

=> marjvniv

ganvixiloT erTadgiliani operatorebis gamoyenebis magaliTi:

using System;

class Unary

Page 15: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

15

{

public static void Main()

{

int unary = 0;

int preIncrement;

int preDecrement;

int postIncrement;

int postDecrement;

int positive;

int negative;

sbyte bitNot;

bool logNot;

preIncrement = ++unary;

Console.WriteLine("წინასწარ გაზრდა: {0}", preIncrement);

preDecrement = --unary;

Console.WriteLine("წინასწარ შემცირება: {0}", preDecrement);

postDecrement = unary--;

Console.WriteLine("შემდეგ შემცირება: {0}", postDecrement);

postIncrement = unary++;

Page 16: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

16

Console.WriteLine("შემდეგ გაზრდა: {0}", postIncrement);

Console.WriteLine("ერთადგილიანის საბოლოო მნიშვნელობა: {0}", unary);

positive = -postIncrement;

Console.WriteLine("დადებითი: {0}", positive);

negative = +postIncrement;

Console.WriteLine("უარყოფითი: {0}", negative);

bitNot = 0;

bitNot = (sbyte)(~bitNot);

Console.WriteLine("ბიტური უარყოფა: {0}", bitNot);

logNot = false;

logNot = !logNot;

Console.WriteLine("ლოგიკური უარყოფა: {0}", logNot);

}

}

ganvixiloT miniWebis instruqcia bitNot = (sbyte) (~bitNot); am instruqciaSi

operatori ~ axdens bitNot-is bitur uaryofas. amitom saWiroa misi gardaqmna

sbyte tipSi, rac sruldeba cxadad (sbyte) gardaqmniT da Sedegi eniWeba bitNot-

ს, xolo ++x axdens jer x-is gazrdas erTiT da Semdeg mis gamoyenebas.

analogiurad xdeba x--da --x-is SemTxvevaSi, mxolod erTiT mcirdeba x-is

Page 17: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

17

mniSvneloba. qvemoT mocemulia programis muSaobis Sedegi, rom SeamowmoT

Tqveni codna operatorebis muSaobis Sesaxeb.

წინასწარ გაზრდა:

წინასწარ შემცირება 0

შემდეგ შემცირება: 0

შემდეგ გაზრდა: -1

ერთადგილიანის საბოლოო მნიშვნელობა: 0

დადებითი: 1

უარყოფითი: -1

ბიტური უარყოფა: -1

ლოგიკური უარყოფა: true

Semdegi programa gviCvenebs binaruli operatorebis gamoyenebas.

using System;

class Binary

{

public static void Main()

{

int x, y, result;

float floatresult;

x = 7;

y = 5;

Page 18: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

18

result = x+y;

Console.WriteLine("x+y: {0}", result);

result = x-y;

Console.WriteLine("x-y: {0}", result);

result = x*y;

Console.WriteLine("x*y: {0}", result);

result = x/y;

Console.WriteLine("x/y: {0}", result);

floatresult = (float)x/(float)y;

Console.WriteLine("x/y: {0}", floatresult);

result = x%y;

Console.WriteLine("x%y: {0}", result);

result += x;

Console.WriteLine("result+=x: {0}", result);

}

}

es programa Sesrulebis Sedegad gamoitans:

Page 19: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

19

x+y: 12

x-y: 2

x*y: 35

x/y: 1

x/y: 1.4

x%y: 2

result+=x: 9

ganvixiloT instruqcia floatresult = (float)x/(float)y; radgan x da y int

tipisaa da maTze sruldeba gayofis operatori, saWiroa isini gadaviyvanoT

float tipSi cxadad. gayofis Sedegi iqneba float tipis da igi mieniWeba

floatresult-s. instruqcia result += x aris result = result + x instruqciis

Semoklebuli Cawera.

masivis tipi. masivi aris erTidaigive tipis mniSvnelobaTa sasruli

mimdevroba. maTTvis mexsierebaSi adgili gamoiyofa mimdevrobiT.

mniSvnelobaze miTiTeba xdeba specialuri wesiT, romelic ganisazRvreba

masivis ganzomilebiTa da TiToeuli ganzomilebis sigrZiT. amgvarad,

masivi ganisazRvreba saxeliT, tipiT, ganzomilebiTa da TiToeuli

ganzomilebis sigrZiT. rom gavecnoT masivis gansazRvras, ganvixiloT

programa da misi Sesrulebis Sedegi:

using System;

class Array

{

public static void Main()

{

int[] myInts = { 5, 10, 15 };

bool[][] myBools = new bool[2][];

Page 20: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

20

myBools[0] = new bool[2];

myBools[1] = new bool[1];

double[,] myDoubles = new double[2, 2];

string[] myStrings = new string[3];

Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}",

myInts[0], myInts[1], myInts[2]);

myBools[0][0] = true;

myBools[0][1] = false;

myBools[1][0] = true;

Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}",

myBools[0][0], myBools[1][0]);

myDoubles[0, 0] = 3.147;

myDoubles[0, 1] = 7.157;

myDoubles[1, 1] = 2.117;

myDoubles[1, 0] = 56.00138917;

Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}",

myDoubles[0, 0], myDoubles[1, 0]);

myStrings[0] = "Joe";

myStrings[1] = "Matt";

myStrings[2] = "Robert";

Page 21: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

21

Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1},

myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]);

}

}

am programis Sesrulebis Sedegia:

myInts[0]: 5, myInts[1]: 10, myInts[2]: 15

myBools[0][0]: true, myBools[1][0]: true

myDoubles[0, 0]: 3.147, myDoubles[1, 0]: 56.00138917

myStrings[0]: Joe, myStrings[1]: Matt, myStrings[2]: Robert

aviRoT instruqcia int[] myInts = { 5, 10, 15 } igi axdens myInts cvladis

gamocxadebas rogorc mTeli tipis erTganzomilebiani masivis da amave

dros axdens mis inicializacias. masivis elementebis gadanomvra iwyeba

nulidan. myInts[0] iqneba xuTi da ase Semdeg. instruqcia double[,]

myDoubles = new double[2, 2] acxadebs myDoubles rogorc double tipis

organzomilebian masivs. new operatori aZlevs sigrZes TiToeul

ganzomilebas. masivis elementebs mniSvnelobebi eniWebaT instruqciebiT:

myDoubles[0, 0] = 3.147;

myDoubles[0, 1] = 7.157;

myDoubles[1, 1] = 2.117;

C#-Si arsebobs meore saxis masivebi, romelTac hqviaT danawevrebuli

masivebi. magaliTad, bool[][] myBools = new bool[2][] aris

organzomilebiani danawevrebuli bool tipis masivi. radganac meore

ganzomilebis elementebi ganixilebian rogorc veqtorebi da TiToeuls

SegviZlia mivceT sxvadasxva sigrZe new operatoriT:

myBools[0] = new bool[2];

myBools[1] = new bool[1];

Page 22: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

22

am veqtorebs mniSvnelobebi mieniWebaT ase:

myBools[0][0] = true;

myBools[0][1] = false;

myBools[1][0] = true;

amgvarad, am leqciaSi Cven SeviswavleT martivi tipis cvladebi,

operatorebi da masivebi - Tu rogor gamoiyenebian isini C# programaSi.

Page 23: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

23

3 leqcia

am leqciaSi Cven SeviswavliT programis marTvis instruqciebs.

if instruqcia. if instruqcia saSualebas gvaZlevs movaxdinoT programis

Sesrulebis ganStoeba garkveuli pirobis mixedviT. gavixiloT magaliTi:

magaliTi 3.1

using System;

class IfSelect

{

public static void Main()

{

string myInput;

int myInt;

Console.Write("გთხოვთ შეიტანოთ რაიმე რიცხვი: ");

myInput = Console.ReadLine();

myInt = Int32.Parse(myInput);

// კონკრეტული გადაწყვეტილება და ბლოკის შესრულება

if (myInt > 0)

{

Console.WriteLine("Tqveni ricxvi {0} metia nulze.", myInt);

}

Page 24: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

24

// konkretuli gadawyvetileba da erTi instruqciis Sesruleba

if (myInt < 0)

Console.WriteLine("Tqveni ricxvi {0} nulze naklebia.", myInt);

// tolia Tu ara

if (myInt != 0)

{

Console.WriteLine("Tqveni ricxvi {0} ar udris nuls.", myInt);

}

else

{

Console.WriteLine("Tqveni ricxvi {0} nulis tolia.", myInt);

}

// მრავალი ალტერნატივა

if (myInt < 0 || myInt == 0)

{

Console.WriteLine("Tqveni ricxvi {0} naklebia an toli nulze.",

myInt);

}

else if (myInt > 0 && myInt <= 10)

{

Page 25: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

25

Console.WriteLine("Tqveni ricxvi {0} aris 0-ze meti da naklebia

an toli 10-ze.", myInt);

}

else if (myInt > 10 && myInt <= 20)

{

Console.WriteLine("Tqveni ricxvi {0} aris 10-ze meti da naklebia

an toli 20-ze.", myInt);

}

else if (myInt > 20 && myInt <= 30)

{

Console.WriteLine("Tqveni ricxvi {0} aris 20-ze meti da naklebia

an toli 30-ze.", myInt);

}

else

{

Console.WriteLine("Tqveni ricxvi {0} aris 30-ze meti.", myInt);

}

}

}

if instruqcias aqvs Semdegi saxe: gasaRebi sityva if Semdeg (<piroba>)

Semdeg bloki Semdeg SeiZleba iyos gasaRebi sityva else da <bloki> an

elseif da igive meordeba rac if SemTxvevaSi, mxolod elseif SeiZleba

gameordes mravaljer da aseTi instruqcia mTavrdeba else da <blokiT>.

<bloki> aris figurul frCxilebSi moTavsebuli erTi an meti instruqcia.

igi gamoiyeneba, roca gvsurs instruqciis adgilas davweroT erTze meti

Page 26: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

26

instruqcia. if instruqciis ganmartebaSi , sadac gvaqvs <bloki> SeiZleba

Seicvalos instruqciiT. <piroba> aris logikuri gamosaxuleba, romlis

mniSvneloba SeiZleba iyos true an false. true SemTxvevaSi sruldeba

(<piroba>)-s Semdeg moTavsebuli bloki. false-s SemTxvevaSi sruldeba

blokis Semdeg moTavsebuli konstruqcia. ganvixiloT programis monakveTi:

Console.Write("gTxovT SeitanoT raime ricxvi ");

myInput = Console.ReadLine();

myInt = Int32.Parse(myInput);

pirvel instruqcias ekranze gamoaqvs - gTxovT SeitanoT raime ricxvi _

da Console.ReadLine() moiTxovs momxmareblisagan akrifos raime striqoni

da daaWiros xeli enter klaviSas. Sedegad myInput-s mieniWeba akrefili

striqoni.Bmesame instruqcias myInput-is mniSvneloba gadahyavs mTel

ricxvad da eniWeba myInt-s.A M Int32.Parse funqcia asrulebs am

gardaqmnas.Y

switch(gadamrTveli) instruqcia. gadamrTveli gamoiyeneba, roca Cven

gvsurs raime cvladis mniSvnelobis mixedviT movaxdinoT programis

ganStoeba. gadamrTvels aqvs Semdegi saxe:

switch (<cvladis saxeli>)

{

case <mniSvneloba1> :

<instruqcia1>

break;

case <mniSvneloba2> :

<instruqcia2>

...

case <mniSvneloban>

Page 27: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

27

<instruqcian>

default:

<instruqcia>

}

Tu cvladis mniSvneloba daemTxveva <mniSvnelobai>-s, maSin sruldeba

<instruqciai> da gadamrTveli amTavrebs muSaobas. Tu cvladis

mniSvneloba ar daemTxveva arcerT mniSvnelobas, maSin sruldeba

<instruqcia> da gadamrTveli amTavrebs muSaobas. ganvixiloT magaliTi:

using System;

class SwitchSelect

{

public static void Main()

{

string myInput;

int myInt;

begin:

Console.Write("გთხოვთ შეიტანოთ რაიმე რიცხვი 1-დან 3-მდე ");

myInput = Console.ReadLine();

myInt = Int32.Parse(myInput);

// gadamrTveli mTeli mniSvnelobiT

Page 28: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

28

switch (myInt)

{

case 1:

Console.WriteLine("Tqveni ricxvia {0}.", myInt);

break;

case 2:

Console.WriteLine("Tqveni ricxvia {0}.", myInt);

break;

case 3:

Console.WriteLine("Tqveni ricxvia {0}.", myInt);

break;

default:

Console.WriteLine("Tqveni ricxvi araa erTsa da sams Soris{0}",

myInt);

break;

}

decide:

Console.Write("akrife \"continue\" rom gaagrZelo an \"quit\" rom

gaaCero programis Sesruleba "); myInput = Console.ReadLine();

// gadamrTveli striqonuli tipis mniSvnelobiT

Page 29: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

29

switch (myInput)

{

case "continue":

goto begin;

case "quit":

Console.WriteLine("Bye.");

break;

default:

Console.WriteLine("Y Tqveni Setana araa swori

{0} ", myInput);

goto decide;

}

}

}

aq ganxilulia gadamrTveli mTeli tipis mniSvnelobiT da gadamrTveli

striqonuli tipis mniSvnelobiT.

ganStoebis instruqciebi

ganStoebis

instruqcia aRwera

break gamodis gadamrTvelis blokidan

continue

agrZelebs cikls ciklis parametris Semdegi

mniSvnelobisaTvis, Tu ciklis parametris mniSvneloba ar

aRemateba ciklis bolo mniSvnelobas. winaaRmdeg

SemTxvevaSi amTavrebs cikls

Page 30: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

30

goto gadadis im Wdeze, romelic weria goto instruqciaSi.

return amTavrebs mimdinare meTods.

throw gamoaqvs Secdomis Setyobineba.

Page 31: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

31

4 leqcia

ciklis instruqciebi

while, do, for da forich instruqciebi

while instruqcia. while instruqciis sintaqsi aseTia:

while (<pirobiTi gamosaxuleba>) {<instruqciebi>},

xolo whi le instruqciis Sesruleba xdeba Semdegnairad: gamoiTvleba

<pirobiTi gamosaxuleba> , Tu misi mniSvnelobaa true, maSin Sesruldeba

figurul frCxilebSi moTavsebuli instruqciebi da kvlav gamoiTvleba

<pirobiTi gamosaxuleba>. Tu misi mniSvnelobaa false, maSin mTavrdeba

while instruqcia. ganvixiloT magaliTi:

using System;

class WhileLoop

{

public static void Main()

{

int myInt = 0;

while (myInt < 10)

{

Console.Write("{0} ", myInt);

myInt++;

}

Console.WriteLine();

Page 32: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

32

}

}

am programaSi myInt-s eniWeba nuli da edareba 10-s, radgan myInt naklebia

10-ze, pirobiT gamosaxulebas eniWeba true da ekranze gamoitaneba myInt-is

mniSvneloba – nuli. Semdeg myInt-is mniSvneloba izrdeba erTiT da

procesi meordeba, sanam myInt ar gaxdeba 10. am dros pirobiTi

gamosaxuleba miiRebs mniSvnelobas false da cikli mTavrdeba. ekranze

gamoitaneba carieli striqoni da programa amTavrebs muSaobas.

do instruqcia. misi sintaqsia: do {<instruqciebi>} while (<pirobiTi

gamosaxuleba>). am SemTxvevaSi jer sruldeba <instruqciebi> da Semdeg

xdeba <pirobiTi gamosaxuleba>-s Semowmeba. amiT gansxvavdeba igi while

instruqciisagan. ganvixiloT magaliTi:

using System;

class DoLoop

{

public static void Main()

{

string myChoice;

do

{

//menu-s gamotana

Console.WriteLine("Cemi misamarTebis wigni \n");

Console.WriteLine("A – daumate axali misamarTi");

Page 33: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

33

Console.WriteLine("D – waSale misamarTi");

Console.WriteLine("M – Seaswore misamarTi");

Console.WriteLine("V – gadaaTvaliere misamarTebi");

Console.WriteLine("Q – gamosvla misamarTebis wignidan\n");

Console.WriteLine("airCie (A,D,M,V,an Q): ");

// momxmareblis arCevanis aReba

myChoice = Console.ReadLine();

// gadawyvetilebis miReba momxmareblis arCevanis mixedviT

switch(myChoice)

{

case "A":

case "a":

Console.WriteLine("axali misamarTis damateba.");

break;

case "D":

case "d":

Console.WriteLine("misamarTis waSla.");

break;

case "M":

Page 34: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

34

case "m":

Console.WriteLine("misamarTis Sesworeba.");

break;

case "V":

case "v":

Console.WriteLine("misamarTebis gadaTvaliereba.");

break;

case "Q":

case "q":

Console.WriteLine("damTavreba“);

break;

default:

Console.WriteLine("{0} araswori arCevani", myChoice);

break;

}

// pauza. rom momxmarebelma naxos Sedegebi

Console.Write("daaWireT Enter-s. rom gaagrZeloT...");

Console.ReadLine();

Console.WriteLine();

} while (myChoice != "Q" && myChoice != "q");

// gagrZeleba

}

Page 35: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

35

}

am programaSi momxmarebeli konkretuli kodis mixedviT irCevs garkveul

moqmedebas misamarTebis wignSi.

for instruqcia. for instruqciis sintaqsia:

for (<inicializacia>; <pirobiTi gamosaxuleba>; <saiteracio sia>)

{<instruqciebi>}

<inicializacia> gansazRvravs ciklis parametrs – mis tipsa da sawyis

mniSvnelobas. Semdeg gamoiTvleba <pirobiTi gamosaxuleba>. Tu misi

mniSvnelobaa true sruldeba <instruqciebi> da <saiteracio sia>-dan

ganisazRvreba ciklis parametris axali mniSvneloba. es procesi meordeba

manam, sanam <pirobiTi gamosaxuleba> ar miiRebs false mniSvnelobas, rac

amTavrebs cikls. ganvixiloT magaliTi:

using System;

class ForLoop

{

public static void Main()

{

for (int i = 0; i < 20; i++)

{

if (i == 10)

break;

if (i % 2 == 0)

continue;

Page 36: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

36

Console.Write("{0} ", i);

}

Console.WriteLine();

}

}

am programas gamoaqvs ekranze i-s kenti mniSvnelobebi 1-dan 10-mde. Tu i=10,

programa amTavrebs cikls, xolo Tu i kentia, ekranze gamoaqvs misi

mniSvneloba da ganixileba ciklis parametris Semdegi mniSvneloba. Tu i

luwia, ganixileba ciklis parametris Semdegi mniSvneloba. instruqcia

break amTavrebs cikls, xolo instruqcia continue agrZelebs cikls ciklis

parametris Semdegi mniSvnelobisaTvis.

forich instruqcia. misi sintaqsia:

forich (<tipi> <saiteracio cvladi> in <sia>) {<instruqciebi>}

<tipi> miuTiTebs <sia>-s elementebis tips. <saiteracio cvladi> aris

ciklis parametri, romelic mniSvnelobebs iRebs <sia>-dan. Tu <sia>-s

tipia int[], maSin <tipi>=int. <saiteracio cvladi> aris cvladis saxeli,

romelic mniSvnelobebs iRebs <sia>-dan. cvladis yoveli

mniSvnelobisaTvis <sia>-dan sruldeba <instruqciebi>, sanam ar amoiwureba

<sia>. ganvixiloT magaliTi:

using System;

class ForEachLoop

{

public static void Main()

{

Page 37: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

37

string[] names = { "Cheryl", "Joe", "Matt", "Robert" };

foreach (string person in names)

{

Console.WriteLine("{0} ", person);

}

}

}

es programa gamoitans ekranze names mniSvnelobebs ekranze da amTavrebs

muSaobas.

amgvarad, Cven am leqciaSi ganvixileT ciklis instruqciis yvela saxe.

Page 38: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

38

5 leqcia

meTodebi

meTodebi saSualebas gvaZleven gamovyoT programis nawili, rogorc

damoukidebeli erTeuli da mas mivmarTod programis sxva adgilidan. aseve

SesaZlebelia misi teqstis modifikacia. misi sintaqsia:

<atributebi> <modifikatorebi> <dasabrunebeli mniSvnelobis tipi>

<meTodis saxeli>(<parametrebi>) {<instruqciebi>}

<atributebi>-s da <modifikatorebi>-s ganvixilavT mogvianebiT.

<dasabrunebeli mniSvnelobis tipi> SeiZleba iyos c#-is nebismieri tipi,

romelic aRniSnavs meTodis dasabrunebeli mniSvnelobis tips. <meTodis

saxeli> aris unikaluri identifikatori, romelic calsaxad gansazRvravs

meTods. <parametrebi> gansazRvraven meTodisaTvis gadasacem da

dasabrunebel informacias. <instruqciebi> gansazRvraven im moqmedebebs,

romlebic unda Seasrulos meTodma. ganvixiloT martivi meTodis

magaliTi.

using System;

class OneMethod

{

public static void Main()

{

string myChoice;

OneMethod om = new OneMethod();

do

{

myChoice = om.getChoice();

// arCevani momxmareblis mier

switch(myChoice)

{

case "A":

case "a":

Page 39: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

39

Console.WriteLine("Tqven gsurT daumatoT misamarTi.");

break;

case "D":

case "d":

Console.WriteLine(“Tqven gsurT misamarTis waSla");

break;

case "M":

case "m":

Console.WriteLine(“Tqven gsurT misamarTis Sesworeba.");

break;

case "V":

case "v":

Console.WriteLine(“Tqven gsurT misamarTebis daTvaliereba.");

break;

case "Q":

case "q":

Console.WriteLine(“damTavreba.");

break;

default:

Console.WriteLine("{0} araswori arCevani", myChoice);

break;

}

// pauza Sedegis dasaTvaliereblad

Console.WriteLine();

Console.Write(“daaWireT Enter-s muSaobis gasagrZeleblad ...");

Console.ReadLine();

Console.WriteLine();

} while (myChoice != "Q" && myChoice != "q");

// muSaobis gagrZeleba, sanam momxmarebeli

//ar daamTavrebs muSaobas

Page 40: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

40

}

string getChoice() {

string myChoice;

// menიus gamotana

Console.WriteLine(“Cemi misamarTebis wigni\n");

Console.WriteLine("A – axali misamarTis damateba");

Console.WriteLine("D – misamarTis waSla");

Console.WriteLine("M – misamarTisSesworeba");

Console.WriteLine("V - misamarTebis daTvaliereba");

Console.WriteLine("Q - damTavreba\n");

Console.Write(“airCieT (A,D,M,V,an Q): ");

// momxmareblis arCevanis aReba

myChoice = Console.ReadLine();

Console.WriteLine();

return myChoice;

}

}

am programaSi ZiriTadi klasia OneMethod, romelSic gansazRvrulia

statikuri main meTodi da getChoice meTodi. Main meTodSi, rom gamoviyenoT

getChoice meTodi, amisaTvis saWiroa SevqmnaT OneMethod klasis obieqti da

gamoviZaxoT am obieqtis getChoice meTodi, radgan igi araa statikuri

meTodi amitom mas pirdapir ver gamoviZaxebT OneMethod klasidan. OneMethod

klasis om obieqti iqmneba instruqciiT

OneMethod om = new OneMethod();

aq OneMethod aris tipi da OneMethod() aris klasis konstruqtori (meTodi,

romelsac igive saxeli aqvs, rac klass). amis Semdeg om obieqtis getChoice

meTodi gamoiZaxeba om.getChoice()-iT. es meTodi abrunebs momxmareblis

arCevans. sxva mxriv es programa igivea rac adrindeli programa. axla

ganvixiloT igive amocanis programa meTodis parametrebis gamoyenebiT.

Page 41: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

41

using System;

class Address

{

public string name;

public string address;

}

class MethodParams

{

public static void Main()

{

string myChoice;

MethodParams mp = new MethodParams();

do

{

// menius Cveneba da momxmareblis arCevani

myChoice = mp.getChoice();

// momxmareblis arCevanis Sesruleba

mp.makeDecision(myChoice);

// pauza Sedegebis dasaTvaliereblad

Console.Write(“daaWire Enter-s gagrZelebisaTvis ");

Console.ReadLine();

Console.WriteLine();

} while (myChoice != "Q" && myChoice != "q");

// gagrZeleba damTavrebamde

}

// menius Cveneba da momxmareblis arCevani

string getChoice()

{

string myChoice;

// menius gamotana

Console.WriteLine(“Cemi misamarTebis wigni");

Page 42: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

42

Console.WriteLine("A – axali misamarTis damateba");

Console.WriteLine("D – misamarTis waSla");

Console.WriteLine("M – misamarTis Sesworeba");

Console.WriteLine("V – misamarTebis daTvaliereba");

Console.WriteLine("Q - damTavreba\n");

Console.WriteLine(“airCie (A,D,M,V,or Q): ");

// arCevanis dafiqsieba

myChoice = Console.ReadLine();

return myChoice;

}

// gadawyvetilebis Sesruleba

void makeDecision(string myChoice)

{

Address addr = new Address();

switch(myChoice)

{

case "A":

case "a":

addr.name = "Joe";

addr.address = "C# Station";

this.addAddress(ref addr);

break;

case "D":

case "d":

addr.name = "Robert";

this.deleteAddress(addr.name);

break;

case "M":

case "m":

addr.name = "Matt";

this.modifyAddress(out addr);

Console.WriteLine(“saxelia {0}.", addr.name);

break;

Page 43: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

43

case "V":

case "v":

this.viewAddresses("Cheryl", "Joe", "Matt", "Robert");

break;

case "Q":

case "q":

Console.WriteLine(“damTavreba.");

break;

default:

Console.WriteLine("{0} araa swori arCevani", myChoice);

break;

}

}

// misamarTis Camateba

void addAddress(ref Address addr)

{

Console.WriteLine(“saxeli: {0}, misamarTi: {1} daemata.", addr.name, addr.address);

}

// misamarTis waSla

void deleteAddress(string name)

{

Console.WriteLine(“Tqven gsurT{0}-is misamarTis waSla.", name);

}

// misamarTis Secvla

void modifyAddress(out Address addr)

{

//Console.WriteLine("saxeli: {0}.", addr.name);

//იწვევს შეცდომას!

addr = new Address();

addr.name = "Joe";

addr.address = "C# Station";

}

Page 44: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

44

// misamarTebis daTvaliereba

void viewAddresses(params string[] names)

{

foreach (string name in names)

{

Console.WriteLine(“saxeli: {0}", name);

}

}

}

es programa igive amocanis realizacias axdens, rac wina programa, magram

gansxvavdeba instruqciebis gamoyenebiT. aq gamoiyeneba parametriani

meTodebi da parametris sxvadasxva saxeebi. parametri SeiZleba iyos

mniSvneloba. aseTi parametris Sesatyvis arguments unda hqondes mxolod

mniSvneloba. parametrs SeiZleba hqondes modifikatori out. aseT

SemTxvevaSi Sesatyvis arguments ar unda Hhqondes mniSvneloba. aseTi

argumentis mniSvneloba unda ganisaZRvros meTodis tanSi da igi

ubrundeba gamomZaxebel programas, sadac SeiZleba am mniSvnelobis

gamoyeneba. parametrs SeiZleba hqondes modifikatori ref, rac niSnavs, rom

Sesatyvisi argumentis mniSvneloba unda iyos misamarTi. an kidev parametrs

SeiZleba hqondes modifikatori params, rac niSnavs, rom Sesatyvisi

argumenti aris cvalebadi sigrZis erTganzomilebiani masivi. am programaSi

mocemulia yvela CamoTvlili saxis parametrebis gamoyeneba. magaliTad,

void addAddress(ref Address addr)

aq, Cven gvaqvs addr aris Address tipis parametri modifikatoriT ref.

void modifyAddress(out Address addr)

aq, parametri aris out modifikatoriT. axla ganvixiloT

void viewAddresses(params string[] names)

Page 45: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

45

aq parametrad gvaqvs names, romelic aris erTganzomilebiani string tipis

masivi modifikatoriT params. es niSnavs, rom Sesatyvis argumentad

SegviZlia aviRoT string tipis erTganzomilebiani nebismieri sigrZis masivi.

Page 46: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

46

6 leqcia

saxelTa areebi (Namespaces)

saxelTa areebi gamoiyeneba imisaTvis, rom zustad mivuTiToT konkretuli

obieqti, roca gansxvavebul obieqtebs aqvT erTidaigive saxeli. amas

vaxerxebT am obieqtebis sxvadasxva saxelTa areSi moTavsebiT. konkretuli

obieqtis miTiTeba xdeba obieqtis saxelze saxelTa ares saxelis

damatebiT. Tu rogor xdeba saxelTa ares Semotana programaSi, amisaTvis

ganvixiloT magaliTi:

// Namespace-is gamocxadeba

using System;

namespace csharp_station

{

class NamespaceCSS

{

public static void Main()

{

Console.WriteLine("This is the new C# Station Namespace.");

}

}

}

saxelTa are ganisazRvreba gasaRebi sityviT namespace, romelsac mosdevs

saxeli da gaxsnili da daxuruli frCxilebi. frCxilebs Soris

moTavsebuli teqsti ekuTvnis saxelTa ares. am magaliTSi Semotanilia

csharp_station saxelTa are, romelsac ekuTvnis klasi NamespaceCSS. saxelTa

areebi SeiZleba iyos erTimeoreSi Cadgmuli. ganvixiloT magaliTi:

using System;

namespace csharp_station

{

namespace tutorial

{

Page 47: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

47

class NamespaceCSS

{

public static void Main()

{

Console.WriteLine("This is the new C# Station Tutorial Namespace.");

}

}

}

}

es magaliTi SeiZleba gadaiweros asec:

using System;

namespace csharp_station.tutorial

{

class NamespaceCSS

{

public static void Main()

{

Console.WriteLine("ეს არის ახალი C# Station Tutorial Namespace.");

}

}

;

instruqcia

namespace csharp_station.tutorial

aRniSnavs Cadgmul saxelTa areebs. wertili miuTiTebs, rom areebi

erTimeoreSia Cadgmuli. axla, ganvixiloT saxelTa areebidan wevrebis

gamoZaxebis magaliTi:

Page 48: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

48

using System;

namespace csharp_station

{

// Cadgmuli namespace

namespace tutorial

{

class myExample1

{

public static void myPrint1()

{

Console.WriteLine("saxelTa ares wevris gamoyenebis pirveli magaliTi.");

}

}

}

class NamespaceCalling

{

public static void Main()

{

tutorial.myExample1.myPrint1();

tutorial.myExample2.myPrint2();

}

}

}

// namespace როგორც ზემოთ ჩადგმული namespace

namespace csharp_station.tutorial

{

class myExample2

public static void myPrint2()

{

Console.WriteLine("saxelTa ares wevris gamoZaxebis meore magaliTi.");

Page 49: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

49

}

}

}

axla ganviiloT using direqtivis gamoyenebis magaliTi:

using System;

using csharp_station.tutorial;

class UsingDirective

{

public static void Main()

{

// namespace –is wevris gamoyeneba

myExample.myPrint();

}

}

namespace csharp_station.tutorial

{

class myExample

{

public static void myPrint()

{

Console.WriteLine(“using direqtivis gamoyenebis magaliTi.");

}

}

}

am magaliTSi direqtivas

using csharp_station.tutorial;

Semohyavs programaSi saxelTa are csharp_station.tutorial. axla ganvixiloT Tu

rogor SevamokloT saxelTa ares grZeli miTiTeba:

Page 50: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

50

using System;

using csTut = csharp_station.tutorial.myExample;

// მეტსახელი

class AliasDirective

{

public static void Main()

{

// namespace –is gamoyeneba

csTut.myPrint();

myPrint();

}

// SesaZlo orazrovani meTodi

static void myPrint()

{

Console.WriteLine("araawevri csharp_station.tutorial.myExample.");

}

}

namespace csharp_station.tutorial

{

class myExample

{

public static void myPrint()

{

Console.WriteLine("es aris wevri - csharp_station.tutorial.myExample.");

}}}

instruqcias

using csTut = csharp_station.tutorial.myExample;

Page 51: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

51

Semohyavs Semamoklebeli saxeli saxelTa aresaTvis

csharp_station.tutorial.myExample

saxelTa ares wevrebi SeiZleba iyos:

klasebi

struqturebi

interfeisebi

gadanomrva

delegatebi

Page 52: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

52

7 leqcia

klasebi

Cven aqamde mravaljer gamoviyeneT klasebi da viciT zogi ram klasebis

Sesaxeb. axla, srulad ganvixilavT klasebs. klasis gansazRvra iwyeba

gasaRebi sityviT class, romelsac mosdevs klasis saxeli da figurul

frCxilebSi moTavsebuli klasis wevrebi. yovel klass aqvs konstruqtori,

romelic aris meTodi da aqvs saxelad klasis saxeli. mas ara aqvs

dasabrunebeli mniSvneloba. igi gamoiZaxeba avtomaturad yovelTvis, roca

xdeba klasis egzemplaris Seqmna. damatebiT, Cven SegviZlia ganvsazRvroT

klasis SigniT mravali konstruqtori da gamoviyenoT nebismieri maTgani

klasis egzemplaris Seqmnisas. konstruqtorebi erTimeoresagan

gansxvavdebian parametrebiT. konstruqtoris daniSnulebaa moaxdinos

klasis wevrebis inicializacia klasis egzemplaris Seqmnisas. klass aqvs

areTve destruqtorebi. destruqtori aris meTodi, romlis saxelia klasis

saxels windarTuli simbolo ~. igi gamoiyeneba klasis daxurvis dros,

rom ganvaTavisuflod klasis mier dakavebuli resursebi. klass SeiZleba

hqondes mravali destruqtori. isini erTimeorisagan gansxvavdebian

parametrebiT. ganvixiloT magaliTi:

using System;

// დამხმარე კლასი

class OutputClass

{

string myString;

// კონსტრუქტორი

public OutputClass(string inputString)

{

myString = inputString;

}

Page 53: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

53

// საობიექტო მეთოდი

public void printString()

{

Console.WriteLine("{0}", myString);

}

// დესტრუქტორი

~OutputClass()

{

// zogierTi resursis ganTavisufleba

}

}

class ExampleClass

{

public static void Main()

{

// OutputClass-is egzemplari

OutputClass outCl = new OutputClass("OutputClass-iT gamoitaneba es");

// OutputClass-is meTodis gamoZaxeba

outCl.printString();

Page 54: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

54

}

}

am programaSi mocemulia konstruqtorisa da destruqtoris magaliTi.

konstruqtori inicializacias ukeTebs klasis elements myString-s. aseve,

destruqtoris tanSi SeiZleba iyos raime resursis ganTavisufleba. am

programaSi iqmneba OutputClass-is obieqti outCl da printString meTods gamoaqvs

ekranze myString-is mniSvneloba. konstruqtorebisa da destruqtorebis

Seqmna programaSi aucilebeli ar aris. aseT SemTxvevaSi avtomaturad

iqmneba gaCumebis principiT erTi konstruqtori da destruqtori

parametrebis gareSe. es konstruqtorebi gamoiyenebian avtomaturad

obieqtis Seqmnisas da obieqtis mier dakavebuli adgilis

gasaTavisufleblad nagavis Semgroveblis mier. aseTi kontruqtorebi ar

arian yovelTvis didad sasargeblo. rom gavxadoT konstruqtorebi ufro

sasargeblo, Cven TviTon SevqmnaT isini mainicializirebelis gamoyenebiT:

public OutputClass() : this("Default Constructor String") { }

aq, konstruqtoris gamoZaxeba xdeba mainicializirebelis saSualebiT. misi

gamoZaxeba xdeba :-iT. this uTiTebs mimdinare obieqts. frCxilebSi

moTavsebuli striqoni aris konstruqtoris argumenti, romelic

inicializacias ukeTebs obieqtis vels. aseTi gziT SesaZlebelia

sxvadasxva konstruqtorebis gamoZaxeba, Tu romeli konstruqtori iqneba

gamoZaxebuli, damokidebulia parametrebis tipsa da raodenobaze. klasis

wevrebi SeiZleba iyvnen egzemplarebi an statikurebi. statikuri wevrebi

gamoiZaxebian ase: <klasis-saxeli> . <statikuri wevri >. vTqvaT, OutputClass

Seicavs statikur meTods

public static void staticPrinter()

{

Console.WriteLine("There is only one of me.");

}

Page 55: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

55

maSin, igi SeiZleba gamoviZaxoT main() meTodidan ase:

OutputClass.staticPrinter();

SeiZleba gvqondes statikuri konstruqtori. igi gamoiyeneba statikuri

velis inicializaciisaTvis. igi unda iyos gamoZaxebuli obieqtis Seqmnamde

da velis gamoyenebamde.

klasis wevrebi SeiZleba iyvnen:

Cadgmuli klasebi

velebi

meTodebi

konstruqtorebi

destruqtorebi

maindeqsireblebi

Tvisebebi

xdomilebebi

delegatebi

Page 56: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

56

8 leqcia

memkvidreobiToba

am leqciaSi SeiswavliT rogor SeqmnaT ZiriTadi da warmoebuli klasebi,

rogor movaxdinoT warmoebuli klasidan ZiriTadi klasis inicializacia,

rogor gamoiZaxoT da damaloT warmoebuli klasidan ZiriTadi klasi.

memkvidreobiToba aris obieqtze orientirebuli daprogramebis ZiriTadi

Tviseba, romelic saSualebas gvaZlevs xelmeored gamoviyenoT ukve

Seqmnili kodi da amiT davzogoT problemis daprogramirebisaTvis saWiro

dro. ganvixiloT magaliTi:

using System;

public class ParentClass

{

public ParentClass()

{

Console.WriteLine("winapari konstruqtori.");

}

public void print()

{

Console.WriteLine("winapari klasi.");

}

}

public class Childclass : ParentClass

Page 57: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

57

{

public ChildClass()

{

Console.WriteLine("Svili konstruqtori.");

}

public static void Main()

{

ChildClass child = new ChildClass();

child.print();

}

}

am magaliTSi Semotanilia ParentClass winapari klasi da Semotanilia misi

konstruqtori, gansazRvrulia meTodi print()da Semdeg modis public class

ChildClass : ParentClass . amiT Semodis memkvidre klasi Childclass da misi

winapari klasia ParentClass . ganvixiloT teqsti:

public static void Main()

{

ChildClass child = new ChildClass();

child.print();

}

radgan es teqsti ekuTvnis Childclass amitom am klasSi ganisazRvra programa

da masSi iqmneba obieqti child. child.print() saSualebiT xdeba winapari klasis

Page 58: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

58

meTodis gamoyeneba. amgvarad, winapari klasi aris ZiriTadi klasi da

ChildClass aris misi memkvidre klasi an rac igivea warmoebuli klasi.

warmoebuli klasis konstruqtori gamoiZaxeba ZiriTadi klasis

konstruqtoris gamoZaxebis Semdeg. axla ganvixiloT magaliTi Tu rogor

ukavSirdeba warmoebuli klasi ZiriTad klass:

using System;

public class Parent

{

string parentString;

public Parent()

{

Console.WriteLine("ZiriTadi konstruqtori.");

}

public Parent(string myString)

{

parentString = myString;

Console.WriteLine(parentString);

}

public void print()

{

Console.WriteLine("ZiriTadi klasi");

}

}

Page 59: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

59

public class Child : Parent

{

public Child() : base("aRebulia warmoebuli klasidan")

{

Console.WriteLine("warmoebuli klasis konstruqtori");

}

public new void print()

{

base.print();

Console.WriteLine("warmoebuli klasi");

}

public static void Main()

{

Child child = new Child();

child.print();

((Parent)child).print();

}

}

public class Child : Parent es instruqcia acxadebs warmoebul klass, xolo

instruqcia

public Child() : base("warmoebuli klasidan")

Page 60: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

60

iZaxebs ZiriTadi klasis konstruqtors, romelsac parametrad aqvs

striqonuli tipis cvladi. es parametri Seicvleba argumentiT

"warmoebuli klasidan". amas uTiTebs : da gasaRebi sityva base. zogjer

SeiZleba dagvWirdes, rom SevqmnaT warmoebul klasSi, sakuTari print

meTodi da gamoviyenoT saWiroebis mixedviT xan ZiriTadi klasis print

meTodi da xan warmoebuli klasis print meTodi.

public new void print();

gasaRebi sityva new saSualebas iZleva warmoebul klasSi gamovacxadoT

axali print meTodi da davmaloT ZiriTadi klasis print meTodi .

child.print()

iZaxebs cxadad warmoebuli klasis print meTods, xolo

((Parent)child).print();

iZaxebs ZiriTadi klasis print meTods. ((Parent)child).print(); axdens

warmoebuli klasis print meTodis Secvlas ZiriTadi klasis print meTodiT.

amgvarad, Cven ukve viciT rogor SevqmnaT ZiriTadi da warmoebuli klasebi

da rogor gamoviZaxoT maTi wevrebi. amave dros, unda gvaxsovdes, rom

wamoebuli klasi aris misi ZiriTadi klasis dazusteba.

Page 61: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

61

9 leqcia

polimorfizmi

am leqciaSi SeiswavliT ra aris polimorfizmi, rogor SeqmnaT

warmoebuli meTodi da rogor gadafaroT igi. rogor gamoiyenoT

polimorfizmi programaSi.

polimorfizmi aris obieqtze orientirebuli daprogramebis erTerTi

ZiriTadi cneba. igi saSualebas gvaZlevs gamoviZaxoT warmoebuli klasis

meTodebi ZiriTadi klasis mimTiTeblebis saSualebiT programis Tvlis

procesSi. es aris moxerxebuli saSualeba, roca gWirdebaT masivis

elementebad aiRoT obieqtebi da gamoiZaxoT am obieqtebis meTodebi. araa

aucilebeli obieqtebi iyvnen erTidaigive tipis. magram Tu isini

dakavSirebuli arian memkvidreobiTobiT, maSin SegiZliaT isini daumatoT

masivs, rogorc warmoebuli tipi da aseve SesaZlebelia maT hqondeT

saerTo meTodebi. SesaZlebelia maTi gamoZaxeba ise, rom ar warmoiSvas

omonimia. ganvixiloT magaliTi:

using System;

public class DrawingObject

{

public virtual void Draw()

{

Console.WriteLine("ZiriTadi dasaxazi obieqti.");

}

}

am magaliTSi mocemulia virtualuri meTodi Draw, romelic SeiZleba

gadafaruli iyos warmoebuli klasis meTodebiT. virtualuri meTodi

Semogvaqvs modifikatoriT virtual. axla, ganvixiloT magaliTi, sadac

Page 62: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

62

warmoebuli klasis meTodebi axdenen ZiriTadi klasis virtualuri

meTodis gadafarvas:

using System;

public class Line : DrawingObject

{

public override void Draw()

{

Console.WriteLine("es aris swori xazi.");

}

}

public class Circle : DrawingObject

{

public override void Draw()

{

Console.WriteLine("es aris wrewiri.");

}

}

public class Square : DrawingObject

{

public override void Draw()

Page 63: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

63

{

Console.WriteLine("es aris kvadrati.");

}

}

virtualuri meTodis gadafarva xdeba modifikatoriT override. gadamfarav

meTodebs unda hqondeT igive signatura da parametrebi rac virtualur

meTods. axla, ganvixiloT polimorfizmis magaliTi:

using System;

public class DrawDemo

{

public static int Main()

{

DrawingObject[] dObj = new DrawingObject[4];

dObj[0] = new Line();

dObj[1] = new Circle();

dObj[2] = new Square();

dObj[3] = new DrawingObject();

foreach (DrawingObject drawObj in dObj)

{

drawObj.Draw();

}

Page 64: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

64

return 0;

}

}

am magaliTSi Semogvaqvs oTxelementiani masivi da masivis elementebs

vaniWebT obieqtebs. Semdeg, ciklSi viyenebT obieqtebis Draw meTods.

Page 65: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

65

10 leqcia

Tvisebebi

am leqciaSi SeiswavliT ra aris Tvisebebi da risTvis gamoiyenebian isini,

rogor movaxdinoT maTi realizacia. aseve, SeiswavliT mxolod wakiTxvad

da mxolod Cawerad Tvisebebs da avtomaturad realizebad Tvisebebs. c#-Si

Tvisebebi Semotanilia imisaTvis, rom davicvaT klasis velebi masSi

Cawerisa an misi wakiTxvisagan. sxva enebSi es keTdeba specialuri

wamkiTxveli da Camweri meTodebis saSualebiT.

Tvisebebis meore upiratesoba velebTan SedarebiT aris is, rom Tqven

SegiZliaT drodadro SecvaloT misi realizacia. velis SemTxvevaSi, misi

tipi unda iyos yovelTvis erTidaigive da Tqven ar SegiZliaT SecvaloT

igi, maSin roca Tqven SegiZliaT SecvaloT Tvisebis Siga realizacia. Tu

klientis ID Tavdapirvelad dayenebulia mTel mniSvnelobaze, Tqven

SegiZliaT daayenoT moTxovna, rom man ver miiRos uaryofiTi mniSvneloba.

amas ver gaakeTebT velis SemTxvevaSi. im enebSi, romlebsac ar gaCniaT

Tvisebebi, Tvisebebis roli SeiZleba Seasrulos specialurad Seqmnilma

meTodebma. axla ganvixiloT Tvisebebis meTodebiT realizaciis magaliTi:

using System;

public class Customer

{

private int m_id = -1;

public int GetID()

{

return m_id;

Page 66: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

66

}

public void SetID(int id)

{

m_id = id;

}

private string m_name = string.Empty;

public string GetName()

{

return m_name;

}

public void SetName(string name)

{

m_name = name;

}

}

public class CustomerManagerWithAccessorMethods

{

public static void Main()

{

Page 67: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

67

Customer cust = new Customer();

cust.SetID(1);

cust.SetName("jemal anTiZe");

Console.WriteLine(

"ID: {0}, saxeli da gvari: {1}",

cust.GetID(),

cust.GetName());

Console.ReadKey();

}

}

am magaliTSi, instruqciiT

private string m_name = string.Empty;

m_name-s vaniWebT cariel mniSvnelobas. amisaTvis viyenebT string klasis

Empty meTods. axla, vnaxoT rogor gavakeToT igive Tvisebebis gamoyenebiT:

using System;

public class Customer

{

private int m_id = -1;

Page 68: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

68

public int ID

{

get

{

return m_id;

}

set

{

m_id = value;

}

}

private string m_name = string.Empty;

public string Name

{

get

{

return m_name;

}

set

{

m_name = value;

}

Page 69: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

69

}

}

public class CustomerManagerWithProperties

{

public static void Main()

{

Customer cust = new Customer();

cust.ID = 1;

cust.Name = "jemal anTiZe";

Console.WriteLine(

"ID: {0}, saxeli da gvari: {1}",

cust.ID,

cust.Name);

Console.ReadKey();

}

}

am magaliTSi Semotanilia klasi Customer, romelSic gvaqvs ori veli int

m_id da string m_name modifikatoriT private. aseve gvaqvs ori Tviseba: ID da

Name, romelTac aqvT get da set. maTi saSualebiT SesaZlebelia aviRoT

velis mniSvneloba da davayenoT maTi mniSvnelobebi gasaRebi sityvis value-

s saSualebiT. instruqcia cust.ID = 1; aniWebs id-s mniSvnelobas erTs

ID-is set-is saSualebiT, xolo gamosaxuleba cust.ID gvaZlevs id-is

mniSvnelobas ID-is get-is saSualebiT. amgvarad, ID da Name saSualebas

Page 70: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

70

gvaZleven rogorc wavikiTxoT Tvisebebis mniSvnelobebi, aseve davayenoT

Tvisebebis mniSvnelobebi. axla, ganvixiloT magaliTi, roca SegviZlia

mxolod Tvisebis mniSvnelobis wakiTxva:

using System;

public class Customer

{

private int m_id = -1;

private string m_name = string.Empty;

public Customer(int id, string name)

{

m_id = id;

m_name = name;

}

public int ID

{

get

{

return m_id;

}

}

Page 71: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

71

public string Name

{

get

{

return m_name;

}

}

}

public class ReadOnlyCustomerManager

{

public static void Main()

{

Customer cust = new Customer(1, "jemal anTiZe");

Console.WriteLine(

"ID: {0}, saxeli da gvari: {1}",

cust.ID,

cust.Name);

Console.ReadKey();

}

}

Page 72: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

72

aq, ID-s da Name-s aqvT mxolod get. amotom, maT SeuZliaT mxolod Tvisebis

mniSvnelobis wakiTxva. analogiurad, Semdeg magaliTSi SegviZlia mxolod

Tvisebis mniSvnelobis dayeneba:

using System;

public class Customer

{

private int m_id = -1;

public int ID

{

set

{

m_id = value;

}

}

private string m_name = string.Empty;

public string Name

{

set

{

Page 73: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

73

m_name = value;

}

}

public void DisplayCustomerData()

{

Console.WriteLine("ID: {0}, saxeli da gvari: {1}", m_id,

m_name);

}

}

public class WriteOnlyCustomerManager

{

public static void Main()

{

Customer cust = new Customer();

cust.ID = 1;

cust.Name = "jemal anTiZe";

cust.DisplayCustomerData();

Console.ReadKey();

}

Page 74: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

74

}

axla, vnaxoT Tu rogor wavikiTxoT da davayenoT Tvisebis mniSvneloba

avtomaturad:

using System;

public class Customer

{

public int ID { get; set; }

public string Name { get; set; }

}

public class AutoImplementedCustomerManager

{

static void Main()

{

Customer cust = new Customer();

cust.ID = 1;

cust.Name = "jemal anTiZe";

Console.WriteLine(

"ID: {0}, saxeli da gvari: {1}",

Page 75: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

75

cust.ID,

cust.Name);

Console.ReadKey();

}

}

rogorc xedavT aseTi midgoma ufro kompaqturia teqstis moculobis

mixedviT.

Page 76: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

76

11 leqcia

maindeqsireblebi

am leqciaSi SeiswavliT ra aris maindeqsirebeli da risTvis gamoiyeneba

igi, rogor SeqmnaT da gadatvirToT isini, rogor SeqmnaT

mravalparametriani maindeqsireblebi. maindeqsirebeli saSualebas aZlevs

klass gamoyenebuli iyos rogorc masivi. klasis SigniT maindeqsirebliT

SeiZleba marToT nebismieri gziT monacemTa koleqciebi. maindeqsirebliT

Tqven SegiZliaT miuTiToT klasis nebismieri monacemi. ganvixiloT

magaliTi:

using System;

// martivi maindeqsireblis magaliTi.

class IntIndexer

{

private string[] myData;

public IntIndexer(int size)

{

myData = new string[size];

for (int i = 0; i < size; i++)

{

myData[i] = "carieli";

}

}

Page 77: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

77

public string this[int pos]

{

get

{

return myData[pos];

}

set

{

myData[pos] = value;

}

}

static void Main(string[] args)

{

int size = 10;

IntIndexer myInd = new IntIndexer(size);

myInd[9] = "raime mniSvneloba";

myInd[3] = "sxva mniSvneloba";

myInd[5] = "nebismieri mniSvneloba";

Console.WriteLine("\nmaindeqsireblis saSualebiT

gamotana\n");

Page 78: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

78

for (int i = 0; i < size; i++)

{

Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);

}

}

}

am magaliTSi, parametriani konstruqtoriT iqmneba masivi, romlis sigrZe

mocemulia parametriT da am masivis elementebs eniWeba mniSvneloba

"carieli". Semdeg, iqmneba maindeqsirebeli get, set da value gasaRebi

sityvebis gamoyenebiT. parametri uTiTebs masivis indeqss. Main meTodSi

xdeba maindeqsireblis gamoyenebiT konkretuli masivis Seqmna da mis

elementebze miTiTeba. Semdegi magaliTi gviCvenebs Tu rogor SeiZleba

maindeqsireblis gadatvirTva:

// gadatvirTuli maindeqsireblis ganxorcieleba.

class OvrIndexer

{

private string[] myData;

private int arrSize;

public OvrIndexer(int size)

{

arrSize = size;

myData = new string[size];

for (int i = 0; i < size; i++)

Page 79: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

79

{

myData[i] = "carieli";

}

}

public string this[int pos]

{

get

{

return myData[pos];

}

set

{

myData[pos] = value;

}

}

public string this[string data]

{

get

{

int count = 0;

for (int i = 0; i < arrSize; i++)

Page 80: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

80

{

if (myData[i] == data)

{

count++;

}

}

return count.ToString();

}

set

{

for (int i = 0; i < arrSize; i++)

{

if (myData[i] == data)

{

myData[i] = value;

}

}

}

}

static void Main(string[] args)

{

int size = 10;

OvrIndexer myInd = new OvrIndexer(size);

Page 81: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

81

myInd[9] = "raime mniSvneloba";

myInd[3] = "sxva mniSvneloba";

myInd[5] = "nebismieri mniSvneloba";

myInd["carieli"] = "ar aqvs mniSvneloba";

Console.WriteLine("\nmaindeqsireblis gamotana\n");

for (int i = 0; i < size; i++)

{

Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);

}

Console.WriteLine("\n \"ar aqvs mniSvneloba\" mniSvnelobaTa

rodenoba: {0}", myInd["ar aqvs mniSvneloba "]);

}

}

pirveli maindeqsirebeli igivea rac wina magaliTSi. meore

maindeqsirebelSi, get-is dros, xdeba parametris mniSvnelobis mqone masivis

elementebis daTvla. set-is dros, Tu masivis elementi udris parametris

mniSvnelobas, maSin masivis elements eniWeba axali mniSvneloba.

roca maindeqsirebels mravali parametri aqvs daiwereba ase:

Page 82: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

82

public object this[int param1, int param2, int param3]

{

get

{

// moqmedebebi da klasis zogierTi monacemis

// dabruneba

}

set

{

// moqmedebebi da klasis zogierTi monacemis

// dayeneba

}

}

Page 83: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

83

12 leqcia

struqturebi

imisaTvis, rom davinaxoT Tu ra gansxvaveba arsebobs struqturebsa da

klasebs Soris, SevadaroT isini erTimeores. pirvel rigSi, struct aris

mniSvnelobis tipi, xolo class aris mimTiTeblis tipi. struqturis

gansazRvris dros, mexsierebaSi gamoiyofa misTvis adgili, maSin roca

klasis gansazRvris dros mexsierebaSi gamoiyofa adgili klasis

mimTiTeblisaTvis. axla, ganvixiloT momxmareblis mier gansazRvruli

struqturis magaliTi:

// klientis struct tipi, romelic warmoadgens marTkuTxovan formas

struct Rectangle

{

private int m_width;

// marTkuTxedis sigane

public int Width

{

get

{

return m_width;

}

set

{

m_width = value;

}

Page 84: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

84

}

// marTkuTxedis simaRle

private int m_height;

// marTkuTxedis simaRlis dayeneba da miReba

public int Height

{

get

{

return m_height;

}

set

{

m_height = value;

}

}

}

am magaliTSi gansazRvrulia struqtura Rectangle, romelsac aqvs ori

Tviseba. struqturis gansazRvra iwyeba sityviT struct, romelsac mosdevs

struqturis saxeli da figurul frCxilebSi moTavsebuli struqturis

wevrebi. rom gamoviyenoT es struqtura, unda movaxdinoT misi

inicializacia da Semdeg gamoviyenoT misi Tvisebebi, rogorc es mocemulia

Semdeg magaliTSi:

Page 85: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

85

using System;

// struct gansazRvrisa da gamoyenebis magaliTi

class StructExample

{

// programaSi Sesasvleli

static void Main()

{

// struqturis realizacia

// sigrZea 1 da simaRle 3

Rectangle rect1 = new Rectangle();

rect1.Width = 1;

rect1.Height = 3;

// rect1-is sigrZisa da simaRlis Cveneba

Console.WriteLine("rect1: {0}:{1}", rect1.Width,

rect1.Height);

Console.ReadKey();

}

}

igive SeiZleba gakeTdes obieqtis inicializaciiT:

Rectangle rect11 = new Rectangle

{

Width = 1,

Page 86: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

86

Height = 3

};

aq, Seqmnilia rect11 marTkuTxedi, gverdebiT 1 da 3.

// klientis struct tipi, romelic warmoadgens marTkuTxeds

struct Rectangle

{

// siganis mocema

private int m_width;

// siganis dayeneba da miReba

public int Width

{

get

{

return m_width;

}

set

{

m_width = value;

}

}

Page 87: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

87

// adgili simaRlisaTvis

private int m_height;

// HsimaRlis dayeneba da miReba

public int Height

{

get

{

return m_height;

}

set

{

m_height = value;

}

}

rom gadatvirToT struqturis konstruqtori unda SemoitanoT cxadad

parametrebiani konstruqtori, rogorc es naCvenebia Semdeg magaliTSi:

// axali marTkuTxedis Seqmna parametrebiani konstruqtoriT

public Rectangle(int width, int height)

{

Page 88: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

88

m_width = width;

m_height = height;

}}

struqturis inicializacia konstruqtoris gadatvirTviT:

using System;

class StructExample

{

static void Main()

{

// rect2 struqturis Seqmna

Rectangle rect2 = new Rectangle(5, 7);

Console.WriteLine("rect2: {0}:{1}", rect2.Width,

rect2.Height);

Console.ReadKey();

}

}

struqturaSi meTodis Semotana:

struct Rectangle

{

private int m_width;

public int Width

Page 89: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

89

{

get

{

return m_width;

}

set

{

m_width = value;

}

}

private int m_height;

public int Height

{

get

{

return m_height;

}

set

{

m_height = value;

}

}

Page 90: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

90

// parametrebiani konstruqtori

public Rectangle(int width, int height)

{

m_width = width;

m_height = height;

}

// mocemuli marTkuTxedis zomis gazrda konkretuli

//marTkuTxedis zomiT

public Rectangle Add(Rectangle rect)

{

// newRect marTkuTxedis Seqmna

Rectangle newRect = new Rectangle();

// marTkuTxedis zomis gazrda

newRect.Width = Width + rect.Width;

newRect.Height = Height + rect.Height;

// newRect-is dabruneba

return newRect;

}

}

struqturis meTodis gamoZaxeba:

Page 91: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

91

using System;

// struqturis gamocxadebisa da gamoyenebis magaliTi

class StructExample

{

static void Main()

{

// rect1 marTkuTxedis Seqmna da inicializacia

Rectangle rect1 = new Rectangle();

rect1.Width = 1;

rect1.Height = 3;

Console.WriteLine("rect1: {0}:{1}", rect1.Width,

rect1.Height);

// rect2 marTkuTxedis Seqmna da inicializacia

Rectangle rect2 = new Rectangle(5, 7);

Console.WriteLine("rect2: {0}:{1}", rect2.Width,

rect2.Height);

// rect3 marTkuTxedis Seqmna da inicializacia rect1.Add-iT

Rectangle rect3 = rect1.Add(rect2);

Console.WriteLine("marTkuTxedi3: {0}:{1}", rect3.Width,

rect3.Height);

Page 92: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

92

Console.ReadKey();

}

}

Console.ReadKey();

}

}

Page 93: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

93

13 leqcia

interfeisebi

am leqciaSi SeiswavliT ra aris interfeisi, rogor SeqmnaT da gamoiyenoT

igi. interfeiss, iseve rogorc klass, aqvs saxeli da igi SeiZleba

Seicavdes xdomilebebis, maindeqsireblebis, meTodebisa Tvisebebis

gamocxadebebs realizaciis gareSe. SeTanxmebiT misi saxeli iwyeba

yovelTvis I asoTi. ganvixiloT magaliTi:

interface IMyInterface

{

void MethodToImplement();

}

am magaliTSi Semotanilia interfeisi IMyInterface , romelic Seicavs erT

sarealizacio meTods MethodToImplemnt(); tanis gareSe. am interfeisis

memkvidre klasSi unda iyos am meTodis gansazRvreba da maT unda hqondeT

erTnairi signatura. axla, vnaxoT am interfeisis gamoyeneba:

class InterfaceImplementer : IMyInterface

{

static void Main()

{

InterfaceImplementer iImp = new InterfaceImplementer();

iImp.MethodToImplement();

}

public void MethodToImplement()

Page 94: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

94

{

Console.WriteLine("MethodToImplement() called.");

}

}

aq, Cven gvaqvs wina interfeisis memkvidre klasi, romelic realizacias

ukeTebs interfeisis meTods da iyenebs am meTods. yuradReba miaqcieT, rom

interfeisis meTods da realizebul meTods aqvT erTnairi signatura. es

savaldebuloa, winaaRmdeg SemTxvevaSi kompilatori mogvcems Secdomas.

interfeisis memkvidre klasi unda Seicavdes interfeisis yvela wevris

realizacias. erTi interfeisi SeiZleba iyos meore interfeisis memkvidre.

ganvixiloT magaliTi:

using System;

interface IParentInterface

{

void ParentInterfaceMethod();

}

interface IMyInterface : IParentInterface

{

void MethodToImplement();

}

class InterfaceImplementer : IMyInterface

Page 95: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

95

{

static void Main()

{

InterfaceImplementer iImp = new InterfaceImplementer();

iImp.MethodToImplement();

iImp.ParentInterfaceMethod();

}

public void MethodToImplement()

{

Console.WriteLine("MethodToImplement() gamoiZaxa.");

}

public void ParentInterfaceMethod()

{

Console.WriteLine("ParentInterfaceMethod() gamoiZaxa.");

}

}

amgvarad, am leqciaSi vaCveneT rogor SevqmnaT interfeisi, rogor

gamoviyenoT Seqmnili interfeisi mis memkvidre klasSi da rogor

gavaxorcieloT interfeisebis memkvidreobiToba.

Page 96: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

96

14 leqcia

delegatebi da xdomilebebi

am leqciaSi SeiswavliT ra aris delegati da xdomileba da rogor

gamoiyenoT isini. C#-Si gvaqvs monacemebis ori tipi – mniSvnelobebi da

mimTiTeblebi. aqamde gaecaniT klasebsa da interfeisebs. axla gaecnobiT

delegatebs, romlebic arian meTodebze mimTiTeblebi.

using System;

// es aris delegatis gamocxadeba

public delegate int Comparer(object obj1, object obj2);

public class Name

{

public string FirstName = null;

public string LastName = null;

public Name(string first, string last)

{

FirstName = first;

LastName = last;

}

// es aris delegate meTodis damamuSavebeli

Page 97: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

97

public static int CompareFirstNames(object name1, object name2)

{

string n1 = ((Name)name1).FirstName;

string n2 = ((Name)name2).FirstName;

if (String.Compare(n1, n2) > 0)

{

return 1;

}

else if (String.Compare(n1, n2) < 0)

{

return -1;

}

else

{

return 0;

}

}

public override string ToString()

{

return FirstName + " " + LastName;

}

Page 98: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

98

}

class SimpleDelegate

{

Name[] names = new Name[5];

public SimpleDelegate()

{

names[0] = new Name("ილია", "ჭავჭავაძე");

names[1] = new Name("აკაკი", "წერეთელი");

names[2] = new Name("ვაჟა", "ფშაველა");

names[3] = new Name("ეგნატე", "ნინოშვილი");

names[4] = new Name("ჭოლა", "ლომთათიძე");

}

static void Main(string[] args)

{

SimpleDelegate sd = new SimpleDelegate();

// ეს არის delegate-ის მყისიერი მდგომარეობა

Comparer cmp = new Comparer(Name.CompareFirstNames);

Page 99: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

99

Console.WriteLine("\nდახარისხებამდე: \n");

sd.PrintNames();

// დაათვალიერეთ delegate-ს არგუმენტი

sd.Sort(cmp);

Console.WriteLine("\nდახარისხების შემდეგ: \n");

sd.PrintNames();

}

// delegate-is parametri

public void Sort(Comparer compare)

{

object temp;

for (int i=0; i < names.Length; i++)

{

for (int j=i; j < names.Length; j++)

{

// delegate "compare" gamoyeneba

// Cveulebrivi meTodis msgavsad

Page 100: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

100

if ( compare(names[i], names[j]) > 0 )

{

temp = names[i];

names[i] = names[j];

names[j] = (Name)temp;

}

}

}

}

public void PrintNames()

{

Console.WriteLine("saxelebi: \n");

foreach (Name name in names)

{

Console.WriteLine(name.ToString());

}

}

}

public static int CompareFirstNames(object name1, object name2)

{

...

Page 101: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

101

}

using System;

using System.Drawing;

using System.Windows.Forms;

// sakuTari delegate

public delegate void Startdelegate();

class Eventdemo : Form

{

// sakuTari event

public event Startdelegate StartEvent;

public Eventdemo()

{

Button clickMe = new Button();

clickMe.Parent = this;

clickMe.Text = "Click Me";

clickMe.Location = new Point(

(ClientSize.Width - clickMe.Width) /2,

(ClientSize.Height - clickMe.Height)/2);

Page 102: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

102

// ხდომილების დამამუშავებელი Delegate დანიშნულია

// ღილაკზე დაწკაპუნების ხდომილებისათვის

clickMe.Click += new EventHandler(OnClickMeClicked);

// ჩვენი custom "Startdelegate" delegateდაენიშნა

// ჩვენს custom "StartEvent" ხდომილებას.

StartEvent += new Startdelegate(OnStartEvent);

// custom event-ის ჩართვა

StartEvent();

}

// es meTodi gamoiZaxeba roca "clickMe" Rilaks daaWerT

public void OnClickMeClicked(object sender, EventArgs ea)

{

MessageBox.Show("You Clicked My Button!");

}

//ეს მეთოდი გამოიძახება, როცა "StartEvent" ხდომილება ჩაირთვება

public void OnStartEvent()

{

MessageBox.Show("I Just Started!");

Page 103: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

103

}

static void Main(string[] args)

{

Application.Run(new Eventdemo());

}

}

public void OnClickMeClicked(object sender, EventArgs ea)

{

MessageBox.Show("თქვენ დააჭირეთ ღილაკს!");

}

Page 104: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

104

15 leqcia

gansakuTrebul SemTxvevaTa damuSaveba

am leqciaSi SeiswavliT ra aris gansakuTrebuli SemTxveva, rogor

ganaxorcieloT Secdomebis damuSavebis standarti try/catch blokiT da

rogor gaaTavisufloT resursebi finally blokiT.

gansakuTrebuli SemTxvevebi arian gauTvaliswinebeli Secdomebi,

romlebic SeiZleba programaSi warmoiSvnen. umetes SemTxvevebSi

SesaZlebelia iwinaswarmetyveloT sad SeiZleba warmoiSvas Secdoma da

miiRoT saTanado zomebi, rom aiciloT igi. magaliTad, SeamowmoT abrunebs

Tu ara funqcia im mniSvnelobas rasac elodebiT. zog SemTxvevebSi

SeuZlebelia iwinaswarmetyveloT igi. magaliTad, failis wakiTxvis

SemTxvevaSi da monacemTa bazasTan muSaobis dros. System.Exeption klasi

iTvaliswinebs sxvadasxva meTodebsa da Tvisebebs, rom miiRoT informacia

imis Sesaxeb Tu ra ar aris swori programaSi. magaliTad, Message Tviseba

iTvaliswinebs informacias Tu ra Secdoma warmoiSva. Stacktrace Tviseba

iZleva iniformacias imis Sesaxeb Tu ra adgilze warmoiSva Secdoma da

gadafaruli ToString() iZleva dawvrilebiT informacias mTeli Secdomis

Sesaxeb. Tu ra gansakuTrebuli SemTxvevebi SeiZleba warmoiSvas

damokidebulia imaze, Tu ra moqmedeba sruldeboda gansakuTrebuli

SemTxvevis warmoSobis momentSi. magaliTad, System.IO.File.OpenRead() meTodis

Sesrulebisas SeiZleba wamoiSvas Semdegi gansakuTrebuli SemTxvevebi:

SecurityException

ArgumentException

PathTooLongException

DirectoryNotFoundException

FileNotFoundException

NotSupportedException

Page 105: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

105

rom daadginoT, konkretulma meTodma ra gansakuTrebuli SemTxvevebi

SeiZleba warmoSvas, unda SexvideT .Net Frmework SDK dokumentaciaSi,

gadaxvideT Reference/Class Library seqciaSi da naxoT Namespace/Class/Method

dokumentacia. mas Semdeg, rac iciT Tu ra gansakuTrebuli SemTxvevebi

SeiZleba warmoiSvas konkretuli meTodis gamoyenebis SemTxvevaSi, Tqven

unda daamuSaoT yoveli gansakuTrebuli SemTxveva try/catch blokebSi. try

blokSi unda SeitanoT gamosacdeli kodi da catch blokSi SesaZlo

gansakuTrebuli SemTxvevebis damamuSavebeli kodi. ganvixiloT magaliTi:

Listing 15-1. Using a try/catch Blocks: tryCatchDemo.cs

using System;

using System.IO;

class tryCatchDemo

{

static void Main(string[] args)

{

try

{

File.OpenRead("NonExistentFile");

}

catch(Exception ex)

{

Console.WriteLine(ex.ToString());

}

}

Page 106: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

106

}

am magaliTSi sacdeli meTodia File.OpenRead, xolo catch blokSi daWera

xdeba Exception gansakuTrebuli SemTxvevis. radgan Exception aris bazuri

gansakuTrebuli SemTxvevis tipi (yvela sxva gansakuTrebuli SemTxveva

aris misgan warmoebuli tipi), amitom nebismieri gansakuTrebuli SemTxveva

iqneba daWerili. axla vnaxoT, Tu rogor daviWiroT konkretuli

gansakuTrebuli SemTxveva:

catch(FileNotFoundException fnfex)

{

Console.WriteLine(fnfex.ToString());

}

catch(Exception ex)

{

Console.WriteLine(ex.ToString());

}

am magaliTSi gvaqvs ori gansauTrebuli SemTxvevis daWera. radgan

FileNotFoundException aris warmoebuli tipi amitom pirvel rigSi moxdeba misi

daWera. sxva Secdomis SemTxvevaSi moxdeba Exception-is daWera.

gansakuTrebuli SemTxvevis dros saWiroa misi Sedegebis likvidacia.

amisaTvis gamoiyeneba finally bloki. igi sruldeba meTodis damTavrebis win.

masSi unda moTavsdes is moqmedebebi, rac saWiroa gansakuTrebuli

SemTxvevis Sedegebis aRmosafxvrelad. ganvixiloT magaliTi:

Listing 15-2. Implementing a finally Block: FinallyDemo.cs

using System;

using System.IO;

Page 107: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

107

class FinallyDemo

{

static void Main(string[] args)

{

FileStream outStream = null;

FileStream inStream = null;

try

{

outStream = File.OpenWrite("DestinationFile.txt");

inStream = File.OpenRead("BogusInputFile.txt");

}

catch(Exception ex)

{

Console.WriteLine(ex.ToString());

}

finally

{

if (outStream != null)

{

outStream.Close();

Console.WriteLine("გარე ნაკადი დაიხურა.");

}

Page 108: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

108

if (inStream != null)

{

inStream.Close();

Console.WriteLine("inStream დაიხურა.");

}

}

}

}

am magaliTSi nakaduri Setana/gamotanis SemTxvevaSi warmoSobili

Secdomisas xdeba saTanado nakadis daxurva.

Page 109: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

109

16 leqcia

atributebis gamoyeneba

am leqciaSi SeiswavliT: ra aris atributi da ratom unda gamoiyenoT igi;

uparametro da mravalparametriani atributebis gamoyenebas; asamblirebuli

kodis, tipis wevrebis da tipis donis atributebis gamoyenebas. atributebi

arian elementebi, romlebic saSualebas gaZleven daumatoT deklaraciuli

informacia Tqvens programebs. es deklaraciuli informacia gamoiyeneba

sxvadasxva daniSnulebiT programis Sesrulebis dros da programis

Seqmnisas gamoyenebiTi programebis Semqmneli saSualebebis mier.

magaliTad, arseboben atributebi rogoricaa DllImportAttribute , romliTac

Tqven SegiZliaT daukavSirdeT WIN32 biblioTekebs. meore atributs

ObsoleteAttribute-s kompilaciis dros gamoaqvs gafrTxileba, rom konkretuli

meTodi ar SeiZleba gamoyenebul iqnes. atributebi arian klasebi,

romlebic SeiZleba daiweron C#-ze da gamoyenebul iqnen Tqveni kodis

gasalamazeblad deklaraciuli informaciiT. am leqciaSi vaCvenebT rogor

gamoviyenoT winaswar arsebuli atributebi programaSi. rac dagexmarebaT

gamoiyenoT mravali sxva winaswar arsebuli atributebi, romlebic

arseboben .NET class biblioTekebSi. atributi iwereba tipis win da Casmulia

kvadratul frCxilebSi. magaliTad, [ObsoluteAtribute], an [Obsolute] sityva

Atribute gareSe. mraval atributs aqvs parametrebis sia, rac saSualebas

gvaZlevs CavrToT damatebiTi informacia atributSi. ganvixiloT magaliTi:

using System;

class BasicAttributeDemo

{

[Obsolete]

public void MyFirstdeprecatedMethod()

{

Page 110: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

110

Console.WriteLine("gamoZaxebulia MyFirstdeprecatedMethod().");

}

[ObsoleteAttribute]

public void MySecondDeprecatedMethod()

{

Console.WriteLine("gamoZaxebulia MySecondDeprecatedMethod().");

}

[Obsolete("ar unda gamoiyenoT es meTodi")]

public void MyThirdDeprecatedMethod()

{

Console.WriteLine("gamoZaxebulia MyThirdDeprecatedMethod().");

}

// usafrTxo programis Zafis gakeTeba COM-isTvis

[STAThread]

static void Main(string[] args)

{

BasicAttributeDemo attrDemo = new BasicAttributeDemo();

attrDemo.MyFirstdeprecatedMethod();

attrDemo.MySecondDeprecatedMethod();

Page 111: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

111

attrDemo.MyThirdDeprecatedMethod();

}

}

[Obsolete]

public void MyFirstdeprecatedMethod()

...

[ObsoleteAttribute]

public void MySecondDeprecatedMethod()

...

Listing 16-2. Using Positional and Named Attribute Parameters: AttributeParamsDemo.cs

using System;

using System.Runtime.InteropServices;

class AttributeParamsDemo

{

[DllImport("User32.dll", EntryPoint="MessageBox")]

static extern int MessageDialog(int hWnd, string msg, string caption, int msgType);

[STAThread]

static void Main(string[] args)

{

Page 112: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

112

MessageDialog(0, "MessageDialog Called!", "DllImport Demo", 0);

}

}

atributs SeiZleba hqondes poziciuri da saxeldebuli parametrebi.

poziciuri parametrebi win unda uswrebdes saxeldebul parametrebs:

Listing 16-3. Using Positional and Named Attribute Parameters: AttributeTargetdemo.cs

using System;

[assembly:CLSCompliant(true)]

public class AttributeTargetdemo

{

public void NonClsCompliantMethod(uint nclsParam)

{

Console.WriteLine("Called NonClsCompliantMethod().");

}

[STAThread]

static void Main(string[] args)

{

uint myUint = 0;

AttributeTargetdemo tgtdemo = new AttributeTargetdemo();

Page 113: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

113

tgtdemo.NonClsCompliantMethod(myUint);

}

}

Page 114: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

114

17 leqcia

gadanomrva

am leqciis mizania: SeviswavloT ra aris gadanomrva; SegeZloT SeqmnaT

axali gadanomris tipebi; SeviswavloT rogor gamoviyenoT isini da

gavecnoT System.Enum tipis meTodebs. gadanomrvebi arian mkacrad

tipizirebuli konstantebi. isini arsebiTad arian unikaluri tipebi,

romlebic saSualebas gaZlevT simboluri saxelebis nacvlad gamoiyenoT

mTeli ricxvebi. nebismieri axali aRniSvna gadanomrvis tipsa da mTel

ricxvs Soris moiTxovs cxad gardaqmnas, radgan isini sxvadasxva tipis

arian. simboluri aRniSvnebi arian Sinaarsoblivi, magram arian

mouxerxebeli misaTiTeblad vidre mTeli ricxvebi. magaliTad, Tu gvaqvs

saxelis mqone mniSvnelobebi: orSabaTi, samSabaTi da ase Semdeg kvira da

maT SevusabamebT mTel ricxvebs 0, 1 da ase Semdeg 6, es ricxvebi

SemdgomSi miuTiTeben kviris dReebs. gadanomrvebi arian aRniSnulni enum

an Enum gasaRebi sityvebiT. C#-is enum tipi Base Class Library (BCL)-is Enum tipis

memkvidrea. gamoiyeneT C#-is enum, rom gansazRvroT axali gadanomrvis

tipebi da gamoiyeneT Enum, rom ganaxorcieloT static enum meTodebi.

ganvixiloT magaliTi, Tu rogor gansazRvroT enum tipi da gamoiyenoT

igi switch instruqciaSi:

using System;

// acxadebs enum

public enum Volume

{

Low,

Medium,

High

}

Page 115: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

115

// enum-is gamoyeneba

class EnumSwitch

{

static void Main()

{

// enum tipis obieqtis Seqmna

Volume myVolume = Volume.Medium;

// gadawyvetilebis miReba enum mniSvnelobis mixedviT

switch (myVolume)

{

case Volume.Low:

Console.WriteLine("The volume has been turned Down.");

break;

case Volume.Medium:

Console.WriteLine("ტომის ნახევარი.");

break;

case Volume.High:

Console.WriteLine("ტომი ჩაირთო.");

break;

}

Page 116: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

116

}

axla ganvixiloT rogor davayenoT Enum Base da rogor movaxdinoT misi

wevrebis inicializacia:

using System;

// acxdebs enum

public enum Volume : byte

{

Low = 1,

Medium,

High

}

class EnumBaseAndMembers

{

static void Main()

{

// Seqmna da inicializacia

// enum tipis obieqtis Seqmna

Volume myVolume = Volume.Low;

// enum mniSvnelobis mixedviT gadawyvetilebis miReba

Page 117: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

117

switch (myVolume)

{

case Volume.Low:

Console.WriteLine("ტომი გამოირთო.");

break;

case Volume.Medium:

Console.WriteLine("ტომის ნახევარი.");

break;

case Volume.High:

Console.WriteLine("ტომი ჩაირთო.");

break;

}

Console.ReadLine();

}

}

enum bazuri tipi gaCumebiT aris int, magram SeiZleba Seicvalos sxva

bazuri tipiT – byte, rogorc es mocemulia instruqciaSi:

public enum Volume : byte

Cveulebriv, sawyisi mniSvneloba iwyeba nuliT, Semdegi mniSvneloba aris

erTi da ase Semdeg. magram, sawyisi mniSvneloba daviwyoT sxva ricxviT,

rogorc es mocemulia instruqciaSi:

Low = 1

axla, ganvixiloT Enum gardaqmnebi da System.Enum gamoyenebis magaliTi:

Listing 17-3. Enum Conversions and using the System.Enum Type: Enumtricks.cs

Page 118: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

118

using System;

// enum-is gamocxadeba

public enum Volume : byte

{

Low = 1,

Medium,

High

}

// gadanomrvebTan muSaobis sxva xerxi

class Enumtricks

{

static void Main(string[] args)

{

// obieqtis Seqmna

Enumtricks enumtricks = new Enumtricks();

// gviCvenebs cxad gardaqmnas int-is Volume-Si

enumtricks.GetEnumFromUser();

//iteracia saxeliT

enumtricks.ListEnumMembersByName();

Page 119: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

119

// iteracia miSvnelobiT

enumtricks.ListEnumMembersByValue();

Console.ReadLine();

}

public void GetEnumFromUser()

{

Console.WriteLine("\n----------------");

Console.WriteLine("zomis dayeneba:");

Console.WriteLine("----------------\n");

Console.Write(@"1 – mcire 2 – saSualo 3 – didi airCieT erTerTi (1, 2, or 3): ");

// momxmareblis mier gansazRvruli mniSvnelobis miReba

string volString = Console.ReadLine();

// cxadi gardaqmna

int volInt = Int32.Parse(volString);

// cxadi gardaqmna

Volume myVolume = (Volume)volInt;

Console.WriteLine();

Page 120: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

120

switch (myVolume)

{

case Volume.Low:

Console.WriteLine("ტომი გამოირთო.");

break;

case Volume.Medium:

Console.WriteLine("ტომის ნახევარი.");

break;

case Volume.High:

Console.WriteLine("ტომი ჩაირთო.");

break;

}

Console.WriteLine();

}

// saxeliT iteracia

public void ListEnumMembersByName()

{

Console.WriteLine("\n---------------------------- ");

Console.WriteLine("ტომის წევრების გადანომრვა სახელით:");

Console.WriteLine("----------------------------\n");

Page 121: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

121

foreach (string volume in Enum.GetNames(typeof(Volume)))

{

Console.WriteLine("ტომის წევრი: {0}\n მნიშვნელობა: {1}",

volume, (byte)Enum.Parse(typeof(Volume), volume));

}

}

// miSvnelobiT iteracia

public void ListEnumMembersByValue()

{

Console.WriteLine("\n----------------------------- ");

Console.WriteLine("ტომის წევრების გადანომრვა მნიშვნელობით:");

Console.WriteLine("-----------------------------\n");

// ყველა მნიშვნელობის (რიცხვითი მნიშვნელობების) მიღება ტომიდან

// enum ტიპი, წევრის სახელის ფორმირება და გამოტანა

foreach (byte val in Enum.GetValues(typeof(Volume)))

{

Console.WriteLine("ტომის მნიშვნელობა: {0}\n წევრი: {1}",

val, Enum.GetName(typeof(Volume), val));

}

}

Page 122: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

122

}

// მომხმარებლის მიერ გათვალისწინებული მნიშვნელობის მიღება

string volString = Console.ReadLine();

int volInt = Int32.Parse(volString);

// ცხადი გარდაქმნის შესრულება int-დან enum ტიპში

Volume myVolume = (Volume)volInt;

// წევრების სახელების სიის მიღება enum ტომიდან,

// რიცხვითი მნიშვნელობის ფორმირება და გამოტანა

foreach (string volume in Enum.GetNames(typeof(Volume)))

{

Console.WriteLine("ტომის წევრი: {0}\n მნიშვნელობა: {1}",

volume, (byte)Enum.Parse(typeof(Volume), volume));

}

// ყველა მნიშვნელობის (რიცხვითი მნიშვნელობების) მიღება Volume

// enum ტიპიდან, წევრის სახელის ფორმირება და გამოტანა

foreach (byte val in Enum.GetValues(typeof(Volume)))

{

Console.WriteLine("Volume Value: {0}\n Member: {1}",

val, Enum.GetName(typeof(Volume), val));

Page 123: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

123

}

18 leqcia

operatorebis gadatvirTva

am leqciaSi SeiswavliT: ra aris operatoris gadatvirTva; rodis aris

mizanSewonili operatoris gadatvirTva; rogor gadatvirToT operatori

da gaecnobiT operatorebis gadatvirTvis wesebs. C#-Si operatorebi

gamoiyenebian bazur tipebze maTematikuri operaciebis Sesasruleblad.

operatoris gadatvirTva niSnavs, gamoviyenoT konkretuli operatori

momxmareblis mier gansazRvrul tipebze operatoris simbolos

Seucvlelad da SecvaloT kodi, romelic operatorma unda Seasrulos.

amisaTvis, momxmarebelma unda Seqmnas tipi da masSi gansazRvros static

meTodi. am meTodis saxelia operatoris simbolo da win ewereba gasaRebi

sityva operator. parametrebis da dasabrunebeli mniSvnelobis tipi unda

iyos momxmareblis mier gansazRvruli tipi. meTodis tani unda iyos

operatoris Sesasrulebeli kodi. operatoris gadatvirTva yovelTvis ar

aris mizanSewonili. magaliTad, Tu operatoris semantika mkveTrad

gansxvavebulia gadatvirTuli operatoris semantikisagan. axla, moviyvanoT

operatoris gadatvirTvisa da misi gamoyenebis magaliTi:

using System;

class Matrix

{

public const int DimSize = 3;

private double[,] m_matrix = new double[DimSize, DimSize];

// inicializacia gamomZaxeblis mier

public double this[int x, int y]

{

Page 124: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

124

get { return m_matrix[x, y]; }

set { m_matrix[x, y] = value; }

}

// matricebis Sekreba

public static Matrix operator +(Matrix mat1, Matrix mat2)

{

Matrix newMatrix = new Matrix();

for (int x=0; x < DimSize; x++)

for (int y=0; y < DimSize; y++)

newMatrix[x, y] = mat1[x, y] + mat2[x, y];

return newMatrix;

}

}

class MatrixTest

{

// matricis inicializacia SemTxveviTi ricxvebiT

public static Random m_rand = new Random();

// Matrix-is testireba

Page 125: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

125

static void Main()

{

Matrix mat1 = new Matrix();

Matrix mat2 = new Matrix();

// matricebis inicializacia

InitMatrix(mat1);

InitMatrix(mat2);

// matricebis gamotana

Console.WriteLine("Matrix 1: ");

PrintMatrix(mat1);

Console.WriteLine("Matrix 2: ");

PrintMatrix(mat2);

// matricebis Sekreba da Sedegis gamotana

Matrix mat3 = mat1 + mat2;

Console.WriteLine();

Console.WriteLine("Matrix 1 + Matrix 2 = ");

PrintMatrix(mat3);

Page 126: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

126

Console.ReadLine();

}

//matricis inicializacia

public static void InitMatrix(Matrix mat)

{

for (int x=0; x < Matrix.DimSize; x++)

for (int y=0; y < Matrix.DimSize; y++)

mat[x, y] = m_rand.NextDouble();

}

// matricis gamotana

public static void PrintMatrix(Matrix mat)

{

Console.WriteLine();

for (int x=0; x < Matrix.DimSize; x++)

{

Console.Write("[ ");

for (int y=0; y < Matrix.DimSize; y++)

{

// gamotanis daformateba

Console.Write("{0,8:#.000000}", mat[x, y]);

Page 127: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

127

if ((y+1 % 2) < 3)

Console.Write(", ");

}

Console.WriteLine(" ]");

}

Console.WriteLine();

}

}

C# moiTxovs operatorebis gadatvirTvis dros Sesruldes Semdegi wesebi:

gadatvirTulma operatorma unda imuSaos momxmareblis mier gansazRvrul

tipze; operatoris gadatvirTvisas unda gadaitvirTos misi Sebrunebuli

operatoriagalc. magaliTad, == operatoris gadatvirTvis dros unda

gadaitvirTos != operatoric; gadatvirTuli operatori muSaobs agreTve

mis Sedgenil operatorzec. magaliTad, gadatvirTuli + operatori

muSaobs += operatorzec.

Page 128: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

128

19 leqcia

Cadgma (inkafsulacia)

am leqciaSi Tqven SeiswavliT: inkafsulaciis obieqtze orientirebul

meTods; klasis wevrebze wvdomis modifikatorebs; obieqtis mdgomareobis

dacvas TvisebebiT; meTodebze kontrolirebul wvdomas; asamblirebuli

kodis tipebis dazustebas inkafsulaciiT. obieqtebs, romlebsac Tqven

qmniT aqvT mdgomareoba qceva. mdgomareoba aris obieqtis konkretuli

monacemi an informacia, romelsac igi Seicavs, xolo qceva xSirad

wamodgenilia obieqtis meTodebiT. agreTve, gaTvaliswinebuli unda iyos,

Tu rogor iqneba gamoyenebuli obieqti. inkafsulacia aris obieqtis Siga

struqturis, monacemebisa და meTodebis realizaciis dafarva programis

sxva nawilisagan, e.i. obieqtSi misTvis saWiro informaciis CarTva ise, rom

sxva obieqtebs ar dasWirdeT misi Sinagani struqturis codna. sxva

obieqtebis dakavSireba masTan xdeba mxolod misi interfeisis saSualebiT.

gare kodis komunikacia obieqtTan SeiZleba ganxorcieldes tipis

meTodebiT ise, rom gare kods ar dasWirdes obieqtis Siga struqturis

codna. obieqtis xilvadoba imarTeba tipsa da tipis wevrebze wvdomis

modifikatorebiT. pirvel rigSi, gavecnoT tipis wevrebze wvdomis

modifikatorebs da rogor gavlenas axdenen isini xilvadobaze.

sazogadod, Tqven unda dafaroT obieqtis Siga mdgomareoba gare kodis

mier masze pidapiri wvdomisagan. Semdeg, unda ganaxorcieloT sxva wevrebi,

rogoric arian meTodebi da Tvisebebi, romlebic fuTaven am mdgomareobas.

es saSualebas gvaZlevs Siga mdgomareoba vcvaloT survilisamebr, maSin

roca meTodebi da Tvisebebi fuTaven ra Siga mdgomareobas, abruneben mis

gare wamodgenas ucvlels. garda amisa, gare kods ar SeuZlia gaafuWos

obieqtis Siga mdgomareoba. obieqtis mdgomareobis inkafsulaciisaTvis,

ganvsazRvroT ra saxis wvdoma SeiZleba hqondes gare kods tipis wevrebze.

amas adgens tipis wevrebze wvdomis modifikatori. Semdeg cxrilSi

CamoTvlilia tipis wevrebze wvdomis modifikatorebi da maTi

mniSvnelobebi.

wvdomis modifikatori aRwera

Page 129: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

129

private wvdoma aqvT mxolod am tipis wevrebs. gaCumebis

principiT es modifikatori igulisxmeba tipis

wevrebisaTvis.

protected wvdoma aqvT mxolod am tipisa da warmoebuli tipis

wevrebs.

internal wvdoma aqvT nebismier kods asamblirebuli kodis

SigniT. gaCumebis principiT es modifikatori

igulisxmeba tipisaTvis.

protected internal wvdoma aqvs kods warmoebuli tipidan an kods igive

asamblirebuli kodidan.

public wvdoma aqvs nebismier kods.

ganvixiloT public modifikatoris gamoyenebis magaliTi:

using System;

class BankAccountPublic

{

public decimal GetAmount()

{

return 1000.00m;

}

}

private modifikatoris gamoyenebis magaliTi:

Page 130: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

130

class BankAccountPrivate

{

private string m_name;

public string CustomerName

{

get { return m_name; }

set { m_name = value; }

}

}

protected meTodis magaliTi:

using System;

class BankAccountProtected

{

public void CloseAccount()

{

ApplyPenalties();

CalculateFinalInterest();

DeleteAccountFromDB();

}

protected virtual void ApplyPenalties()

Page 131: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

131

{

// account-დან გამოყვანა

}

protected virtual void CalculateFinalInterest()

{

// account-ის დამატება

}

protected virtual void DeleteAccountFromDB()

{

// data entry personnel-ისთვის შეტყობინების გაგზავნა

}

}

warmoebuli klasis wevrebi iyeneben bazuri klasis protected wevrebs:

using System;

class SavingsAccount : BankAccountProtected

{

protected override void ApplyPenalties()

{

Console.WriteLine("Savings Account Applying Penalties");

Page 132: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

132

}

protected override void CalculateFinalInterest()

{

Console.WriteLine("Savings Account Calculating Final Interest");

}

protected override void DeleteAccountFromDB()

{

base.DeleteAccountFromDB();

Console.WriteLine("Savings Account Deleting Account from DB");

}

}

warmoebuli klasis wevrebi iyeneben bazuri klasis protected wevrebs:

using System;

class CheckingAccount : BankAccountProtected

{

protected override void ApplyPenalties()

{

Console.WriteLine("Checking Account Applying Penalties");

}

Page 133: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

133

protected override void CalculateFinalInterest()

{

Console.WriteLine("Checking Account Calculating Final Interest");

}

protected override void DeleteAccountFromDB()

{

base.DeleteAccountFromDB();

Console.WriteLine("Checking Account Deleting Account from DB");

}

}

BankAccountProtected[] bankAccts = new BankAccountProtected[2];

bankAccts[0] = new SavingsAccount();

bankAccts[1] = new CheckingAccount();

foreach (BankAccountProtected acct in bankAccts)

{

// public method-ის გამოძახება, რომელიც იძახებს protected virtual method-ებს

acct.CloseAccount();

}

Page 134: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

134

klasebs aqvT mxolod ori wvdomis modifikatori: internal da public. internal

igulisxmeba gaCumebiT da public niSnavs, rom am klass SeiZleba mivwvdeT

biblioTekis garedan.

l

Page 135: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

135

20 leqcia

ZiriTadi koleqciebi

public class Customer

{

public Customer(int id, string name)

{

ID = id;

Name = name;

}

private int m_id;

public int ID

{

get { return m_id; }

set { m_id = value; }

}

private string m_name;

public string Name

{

Page 136: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

136

get { return m_name; }

set { m_name = value; }

}

}

Dictionary<int, Customer> customers = new Dictionary<int, Customer>();

Customer cust1 = new Customer(1, "Cust 1");

Customer cust2 = new Customer(2, "Cust 2");

Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1);

customers.Add(cust2.ID, cust2);

customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers)

{

Console.WriteLine(

"Customer ID: {0}, Name: {1}",

custKeyVal.Key,

custKeyVal.Value.Name);

}

Page 137: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

137

Listing 20-1. Introduction to Using Generic Collections with an Example of the List<T> and

Dictionary<TKey, TValue> Generic Collections

using System;

using System.Collections.Generic;

public class Customer

{

public Customer(int id, string name)

{

ID = id;

Name = name;

}

private int m_id;

public int ID

{

get { return m_id; }

set { m_id = value; }

}

private string m_name;

Page 138: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

138

public string Name

{

get { return m_name; }

set { m_name = value; }

}

}

class Program

{

static void Main(string[] args)

{

List<int> myInts = new List<int>();

myInts.Add(1);

myInts.Add(2);

myInts.Add(3);

for (int i = 0; i < myInts.Count; i++)

{

Console.WriteLine("MyInts: {0}", myInts[i]);

}

Dictionary<int, Customer> customers = new Dictionary<int, Customer>();

Page 139: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

139

Customer cust1 = new Customer(1, "Cust 1");

Customer cust2 = new Customer(2, "Cust 2");

Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1);

customers.Add(cust2.ID, cust2);

customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers)

{

Console.WriteLine(

"Customer ID: {0}, Name: {1}",

custKeyVal.Key,

custKeyVal.Value.Name);

}

Console.ReadKey();

}

}

Page 140: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

140

21 leqcia

anonimuri meTodebi

Listing 21-1. Implementing an Anonymous Method

using System.Windows.Forms;

public partial class Form1 : Form

{

public Form1()

{

Button btnHello = new Button();

btnHello.Text = "სალამი";

btnHello.Click +=

delegate

{

MessageBox.Show("სალამი");

};

Controls.Add(btnHello);

}

}

Page 141: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

141

Listing 21-2. Using Parameters with Anonymous Methods

using System;

using System.Windows.Forms;

public partial class Form1 : Form

{

public Form1()

{

Button btnHello = new Button();

btnHello.Text = "სალამი";

btnHello.Click +=

delegate

{

MessageBox.Show("სალამი");

};

Button btnGoodBye = new Button();

btnGoodBye.Text = "მშვიდობით";

btnGoodBye.Left = btnHello.Width + 5;

btnGoodBye.Click +=

delegate(object sender, EventArgs e)

Page 142: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

142

{

string message = (sender as Button).Text;

MessageBox.Show(message);

};

Controls.Add(btnHello);

Controls.Add(btnGoodBye);

}

}

Page 143: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

143

22 leqcia

C#-is tipebis Sesaxeb

am leqciaSi Tqven SeiswavliT: risTvis aris saWiro tipebis usafrTxoeba;

rogor gardaqmnaT erTi tipi meoreSi; ufro detalu rad SeiswavliT

mimTiTeblian da mniSvnelobian tipebs da Sinaarsobliv gansxvavebas maT

Soris. Tu erTi tipis cvlads mianiWebT meore tipis cvlads aseT

SemTxvevaSi SeiZleba warmoiSvas problemebi. zogi problema SeiZleba iyos

acilebadi da zogi ara. acilebadi problemis SemTxvevaSi iyeneben

aracxad an cxad gardaqmnebs. cxadi gardaqmnis SemTxvevaSi iyeneben

gardaqmnis operators (X), xolo aracxadi gardaqmna niSnavs, rom cxadi

gardaqmnis operatori araa gamoyenebuli da aseT SemTxvevaSi kompilatori

cdilobs TviTon Seasrulos gardaqmna da Tu es SeuZlebelia

kompilatori iZleva Secdomis Setyobinebas. zogjer cxadi gardaqmna araa

mizanSewonili, radgan SeiZleba gamoiwvios sizustis dakargva. magaliTad,

double tipis mniSvnelobis int tipis mniSvnelobad gardaqmnis dros.

ganvixiloT cxadi da aracxadi gardaqmnis magaliTi:

using System;

class Program

{

static void Main()

{

float lengthFloat = 7.35f;

// sizustis dakargvis SesaZlebloba

int lengthInt = (int)lengthFloat;

Page 144: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

144

// uproblemo aracxadi gardaqmna

double lengthDouble = lengthInt;

Console.WriteLine("lengthInt =

" + lengthInt);

Console.WriteLine("lengthDouble

= " + lengthDouble);

Console.ReadKey();

}

}

erTi mimTiTeblis miniWebisas meoresTvis xdeba misamarTebis da ara

obieqtebis kopireba. ganvixiloT magaliTi:

using System;

class Employee

{

private string m_name;

public string Name

{

get { return m_name; }

Page 145: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

145

set { m_name = value; }

}

}

class Program

{

static void Main()

{

Employee joe = new Employee();

joe.Name = "Joe";

Employee bob = new Employee();

bob.Name = "Bob";

Console.WriteLine("Original Employee Values:");

Console.WriteLine("joe = " + joe.Name);

Console.WriteLine("bob = " + bob.Name);

// cvladisaთvis mimTiTeblis miniWeba

bob = joe;

Console.WriteLine();

Console.WriteLine("Values After Reference Assignment:");

Page 146: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

146

Console.WriteLine("joe = " + joe.Name);

Console.WriteLine("bob = " + bob.Name);

joe.Name = "Bobbi Jo";

Console.WriteLine();

Console.WriteLine("Values After Changing One Instance:");

Console.WriteLine("joe = " + joe.Name);

Console.WriteLine("bob = " + bob.Name);

Console.ReadKey();

}

}

mniSvnelobiani tipis cvladebis erTimeoreze miniWebisas xdeba obieqtis

mniSnelobis kopireba da orive cvladi miiRebs erTidaigive mniSvnelobas.

ganvixiloT magaliTi:

using System;

struct Height

{

private int m_inches;

Page 147: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

147

public int Inches

{

get { return m_inches; }

set { m_inches = value; }

}

}

class Program

{

static void Main()

{

Height joe = new Height();

joe.Inches = 71;

Height bob = new Height();

bob.Inches = 59;

Console.WriteLine("საწყისი სიმაღლის

მნიშვნელობები:");

Console.WriteLine("joe = " + joe.Inches);

Console.WriteLine("bob = " + bob.Inches);

Page 148: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

148

bob = joe;

Console.WriteLine();

Console.WriteLine("Values After

Value Assignment:");

Console.WriteLine("joe = " + joe.Inches);

Console.WriteLine("bob = " + bob.Inches);

joe.Inches = 65;

Console.WriteLine();

Console.WriteLine("Values After

Changing One Instance:");

Console.WriteLine("joe = " + joe.Inches);

Console.WriteLine("bob = " + bob.Inches);

Console.ReadKey();

}

}

23 leqciaU

Page 149: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

149

null tipis gamoyeneba

am leqciaSi SeiswavliT: ra aris carielmniSvnelobiani tipi;

rogor gamoacxadoT da gamoiyenoT igi. problema mdgomareobs imaSi, rom

roca raime cvlads ara aqvs miniWebuli mniSvneloba da mas iyenebT

gamosaxulebaSi, aseT SemTxvevaSi Tvlis dros wamoiSveba Secdoma da

Tqveni programa ganicdis wyvetas. amis acileba iqneboda SesaZlebeli,

Tqven rom SegZlebodaT SegemowmebinaT aqvs Tu ara am cvlads mniSvneloba.

amis saSualebas iZleva carielmniSvnelobiani (null) tipis Semotana C#-Si.

magaliTad, carielmniSvnelobiani mTeli tipi niSnavs, rom mTeli

mniSvnelobebis simravles emateba specialuri mniSvneloba null, romelic

aRiSnavs, rom cvlads ara aqvs miniWebuli mniSvneloba. magaliTad, igi

gvexmareba davadginoT mTeli tipis cvlads aqvs Tu ara mniSvneloba da

amiT aviciloT misi gamoyeneba gamosaxulebaSi, roca mas ar aqvs

mniSvneloba. carielmniSvnelobiani tipis aRsaniSnavad tipis saxels

boloSi miewereba ? niSani. ganvixiloT magaliTi:

int a;

int? b;

if (b == null)

{

a = 0;

}

else

{

a = (int)b;

}

am magaliTSi, a-s eniWeba b, Tu b-s ara aqvs null mniSvneloba, winaaRmdeg

SemTxvevaSi nuli. SevniSnoT, rom carielmniSvnelobiani cvladis

Page 150: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

150

aracarielmniSvnelobiani Sesatyvisi tipis cvladze miniWebisas

aucilebelia cxadi gardaqmna. gansakuTrebiT mosaxerxebelia

carielmniSvnelobiani tipebis gamoyeneba monacemTa bazebTan muSaobisas.

monacemTa bazis carielmniSvnelobian tips unda SeuTanadoT C#-Si

carielmniSvnelobiani tipi. amiT mogecemaT saSualeba aiciloT progamis

wyveta, roca monacemTa bazis Canaweris vels aqvs carieli mniSvneloba.

Tqven SegiZliaT cvlads mianiWoT carieli mniSvneloba:

int? a = null;

an kidev

bull c = a == null;

C#-Si arsebobs specialuri oradgiliani operatori ?? , romelic muSaobs

ase: Tu marcxena operandis mniSvnelobaa null, maSin gamoiTvleba marjvena

operandi, sxva SemTxvevaSi marcxena operandi. magaliTad:

int b = a ?? 0;

sadac

int? a;

amgvarad, C#-is carielmniSvnelobiani tipi gvexmareba mTel rig

SemTxvevebSi SevadginoT efeqturi programa.

magaliTebi

failis Seqmna da wakiTxva

Page 151: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

151

using System;

using System.IO;

class SavarjiSo

{

public static void Main()

{

string path = @"c:\temp\savarjiSo.txt";

if (!File.Exists(path))

{

// ფაილის შექმნა

using (StreamWriter sw = File.CreateText(path))

{

sw.WriteLine("ეს არის საცდელი ფაილი");

sw.WriteLine("შექმენი,");

sw.WriteLine("შემდეგ წაიკითხე");

}

}

// ფაილის გახსნა წასაკითხად

using (StreamReader sr = File.OpenText(path))

{

string s = "";

Page 152: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

152

while ((s = sr.ReadLine()) != null)

{

Console.WriteLine(s);

}

}

}

}

masivis gamoyeneba

// arrays.cs

using System;

class DeclareArraysSample

{

public static void Main()

{

// erTganzomilebiani masivi

int[] numbers = new int[5];

// mravalganzomilebiani masivi

string[,] names = new string[5,4];

// მასივების მასივი (დაკბილული მასივი)

byte[][] scores = new byte[5][];

// dakbiluli masivis Seqmna

Page 153: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

153

for (int i = 0; i < scores.Length; i++)

{

scores[i] = new byte[i+3];

}

// masivis striqonis sigrZis gamotana

for (int i = 0; i < scores.Length; i++)

{

Console.WriteLine("Length of row {0} is {1}", i,

scores[i].Length);

}

}

}

atributebis gamoyeneba

//Copyright (C) Microsoft Corporation. All rights reserved.

// AttributesTutorial.cs

// This example shows the use of class and method attributes.

using System;

using System.Reflection;

Page 154: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

154

using System.Collections;

// The IsTested class is a user-defined custom attribute class.

// It can be applied to any declaration including

// - types (struct, class, enum, delegate)

// - members (methods, fields, events, properties, indexers)

// It is used with no arguments.

public class IsTestedAttribute : Attribute

{

public override string ToString()

{

return "testirebulia";

}

}

// The AuthorAttribute class is a user-defined attribute class.

// It can be applied to classes and struct declarations only.

// It takes one unnamed string argument (the author's name).

// It has one optional named argument Version, which is of type

int.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]

public class AuthorAttribute : Attribute

{

// This constructor specifies the unnamed arguments to the

attribute class.

Page 155: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

155

public AuthorAttribute(string name)

{

this.name = name;

this.version = 0;

}

// This property is readonly (it has no set accessor)

// so it cannot be used as a named argument to this attribute.

public string Name

{

get

{

return name;

}

}

// This property is read-write (it has a set accessor)

// so it can be used as a named argument when using this

// class as an attribute class.

public int Version

{

get

{

return version;

Page 156: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

156

}

set

{

version = value;

}

}

public override string ToString()

{

string value = "Author : " + Name;

if (version != 0)

{

value += " Version : " + Version.ToString();

}

return value;

}

private string name;

private int version;

}

// Here you attach the AuthorAttribute user-defined custom

attribute to

// the Account class. The unnamed string argument is passed to the

Page 157: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

157

// AuthorAttribute class's constructor when creating the

attributes.

[Author("Joe Programmer")]

class Account

{

// Attach the IsTestedAttribute custom attribute to this

method.

[IsTested]

public void AddOrder(Order orderToAdd)

{

orders.Add(orderToAdd);

}

private ArrayList orders = new ArrayList();

}

// Attach the AuthorAttribute and IsTestedAttribute custom

attributes

// to this class.

// Note the use of the 'Version' named argument to the

AuthorAttribute.

[Author("Jane Programmer", Version = 2), IsTested()]

class Order

{

// add stuff here ...

Page 158: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

158

}

class MainClass

{

private static bool IsMemberTested(MemberInfo member)

{

foreach (object attribute in

member.GetCustomAttributes(true))

{

if (attribute is IsTestedAttribute)

{

return true;

}

}

return false;

}

private static void DumpAttributes(MemberInfo member)

{

Console.WriteLine("Attributes for : " + member.Name);

foreach (object attribute in

member.GetCustomAttributes(true))

{

Console.WriteLine(attribute);

}

Page 159: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

159

}

public static void Main()

{

// display attributes for Account class

DumpAttributes(typeof(Account));

// display list of tested members

foreach (MethodInfo method in

(typeof(Account)).GetMethods())

{

if (IsMemberTested(method))

{

Console.WriteLine("წევრი {0} ტესტირებულია!",

method.Name);

}

else

{

Console.WriteLine("წევრი {0} არაა ტესტირებული!",

method.Name);

}

}

Console.WriteLine();

// display attributes for Order class

Page 160: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

160

DumpAttributes(typeof(Order));

// display attributes for methods on the Order class

foreach (MethodInfo method in

(typeof(Order)).GetMethods())

{

if (IsMemberTested(method))

{

Console.WriteLine("წევრი {0} ტესტირებულია!",

method.Name);

}

else

{

Console.WriteLine("წევრი {0} არაა ტესტირებული!",

method.Name);

}

}

Console.WriteLine();

}

}

tokenebis gamocnoba

//Copyright (C) Microsoft Corporation. All rights reserved.

// tokens.cs

using System;

Page 161: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

161

// The System.Collections namespace is made available:

using System.Collections;

// Declare the Tokens class:

public class Tokens : IEnumerable

{

private string[] elements;

Tokens(string source, char[] delimiters)

{

// Parse the string into tokens:

elements = source.Split(delimiters);

}

// IEnumerable Interface Implementation:

// Declaration of the GetEnumerator() method

// required by IEnumerable

public IEnumerator GetEnumerator()

{

return new TokenEnumerator(this);

}

// Inner class implements IEnumerator interface:

private class TokenEnumerator : IEnumerator

Page 162: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

162

{

private int position = -1;

private Tokens t;

public TokenEnumerator(Tokens t)

{

this.t = t;

}

// Declare the MoveNext method required by IEnumerator:

public bool MoveNext()

{

if (position < t.elements.Length - 1)

{

position++;

return true;

}

else

{

return false;

}

}

// Declare the Reset method required by IEnumerator:

Page 163: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

163

public void Reset()

{

position = -1;

}

// Declare the Current property required by IEnumerator:

public object Current

{

get

{

return t.elements[position];

}

}

}

// Test Tokens, TokenEnumerator

static void Main()

{

// Testing Tokens by breaking the string into tokens:

Tokens f = new Tokens("ესაა კარგად დაწერილი პროგრამა.",

new char[] {' ','-'});

foreach (string item in f)

{

Page 164: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

164

Console.WriteLine(item);

}

}

}

struqturis gamoyeneba

//Copyright (C) Microsoft Corporation. All rights reserved.

// struct1.cs

using System;

struct SimpleStruct

{

private int xval;

public int X

{

get

{

return xval;

}

set

{

if (value < 100)

xval = value;

Page 165: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

165

}

}

public void DisplayX()

{

Console.WriteLine("დამახსოვრებული მნიშვნელობა: {0}", xval);

}

}

class TestClass

{

public static void Main()

{

SimpleStruct ss = new SimpleStruct();

ss.X = 5;

ss.DisplayX();

}

}

Tvisebebis gamoyeneba

//Copyright (C) Microsoft Corporation. All rights reserved.

// person.cs

using System;

class Person

Page 166: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

166

{

private string myName ="N/A";

private int myAge = 0;

// string tipis Tvisebis gamocxadeba

public string Name

{

get

{

return myName;

}

set

{

myName = value;

}

}

// int tipis Tvisebis gamocxadeba:

public int Age

{

get

{

return myAge;

}

Page 167: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

167

set

{

myAge = value;

}

}

public override string ToString()

{

return "Name = " + Name + ", Age = " + Age;

}

public static void Main()

{

Console.WriteLine("Simple Properties");

// axali obieqtis Seqmna

Person person = new Person();

// name da age mniSvnelobebis gamotana

Console.WriteLine("Person details - {0}", person);

// person obieqtis mniSvnelobebis dayeneba

person.Name = "Joe";

person.Age = 99;

Page 168: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

168

Console.WriteLine("პიროვნების დეტალები - {0}", person);

// Age Tvisebis mniSvnelobis gazrda

person.Age += 1;

Console.WriteLine("პიროვნების დეტალები - {0}", person);

}

}

maindeqsireblis gamoyeneba

//Copyright (C) Microsoft Corporation. All rights reserved.

// indexer.cs

// არგუმენტები: indexer.txt

using System;

using System.IO;

// Class to provide access to a large file

// as if it were a byte array.

public class FileByteArray

{

Stream stream; // Holds the underlying stream

Page 169: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

169

// used to access the file.

// Create a new FileByteArray encapsulating a particular file.

public FileByteArray(string fileName)

{

stream = new FileStream(fileName, FileMode.Open);

}

// Close the stream. This should be the last thing done

// when you are finished.

public void Close()

{

stream.Close();

stream = null;

}

// Indexer to provide read/write access to the file.

public byte this[long index] // long is a 64-bit integer

{

// Read one byte at offset index and return it.

get

{

byte[] buffer = new byte[1];

stream.Seek(index, SeekOrigin.Begin);

stream.Read(buffer, 0, 1);

Page 170: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

170

return buffer[0];

}

// Write one byte at offset index and return it.

set

{

byte[] buffer = new byte[1] {value};

stream.Seek(index, SeekOrigin.Begin);

stream.Write(buffer, 0, 1);

}

}

// Get the total length of the file.

public long Length

{

get

{

return stream.Seek(0, SeekOrigin.End);

}

}

}

// Demonstrate the FileByteArray class.

// Reverses the bytes in a file.

public class Reverse

Page 171: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

171

{

public static void Main(String[] args)

{

// Check for arguments.

if (args.Length != 1)

{

Console.WriteLine("Usage : Indexer <filename>");

return;

}

// Check for file existence

if (!System.IO.File.Exists(args[0]))

{

Console.WriteLine("File " + args[0] + " not

found.");

return;

}

FileByteArray file = new FileByteArray(args[0]);

long len = file.Length;

// Swap bytes in the file to reverse it.

for (long i = 0; i < len / 2; ++i)

{

Page 172: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

172

byte t;

// Note that indexing the "file" variable invokes

the

// indexer on the FileByteStream class, which

reads

// and writes the bytes in the file.

t = file[i];

file[i] = file[len - i - 1];

file[len - i - 1] = t;

}

file.Close();

}

}

delegatebis gamoyeneba

//Copyright (C) Microsoft Corporation. All rights reserved.

// bookstore.cs

using System;

// A set of classes for handling a bookstore:

namespace Bookstore

Page 173: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

173

{

using System.Collections;

// Describes a book in the book list:

public struct Book

{

public string Title; // Title of the book.

public string Author; // Author of the book.

public decimal Price; // Price of the book.

public bool Paperback; // Is it paperback?

public Book(string title, string author, decimal price, bool

paperBack)

{

Title = title;

Author = author;

Price = price;

Paperback = paperBack;

}

}

// Declare a delegate type for processing a book:

public delegate void ProcessBookDelegate(Book book);

Page 174: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

174

// Maintains a book database.

public class BookDB

{

// List of all books in the database:

ArrayList list = new ArrayList();

// Add a book to the database:

public void AddBook(string title, string author, decimal

price, bool paperBack)

{

list.Add(new Book(title, author, price, paperBack));

}

// Call a passed-in delegate on each paperback book to

process it:

public void ProcessPaperbackBooks(ProcessBookDelegate

processBook)

{

foreach (Book b in list)

{

if (b.Paperback)

// Calling the delegate:

processBook(b);

}

}

Page 175: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

175

}

}

// Using the Bookstore classes:

namespace BookTestClient

{

using Bookstore;

// Class to total and average prices of books:

class PriceTotaller

{

int countBooks = 0;

decimal priceBooks = 0.0m;

internal void AddBookToTotal(Book book)

{

countBooks += 1;

priceBooks += book.Price;

}

internal decimal AveragePrice()

{

return priceBooks / countBooks;

}

Page 176: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

176

}

// Class to test the book database:

class Test

{

// Print the title of the book.

static void PrintTitle(Book b)

{

Console.WriteLine(" {0}", b.Title);

}

// Execution starts here.

static void Main()

{

BookDB bookDB = new BookDB();

// Initialize the database with some books:

AddBooks(bookDB);

// Print all the titles of paperbacks:

Console.WriteLine("Paperback Book Titles:");

// Create a new delegate object associated with the

static

// method Test.PrintTitle:

Page 177: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

177

bookDB.ProcessPaperbackBooks(new

ProcessBookDelegate(PrintTitle));

// Get the average price of a paperback by using

// a PriceTotaller object:

PriceTotaller totaller = new PriceTotaller();

// Create a new delegate object associated with the

nonstatic

// method AddBookToTotal on the object totaller:

bookDB.ProcessPaperbackBooks(new

ProcessBookDelegate(totaller.AddBookToTotal));

Console.WriteLine("Average Paperback Book Price:

${0:#.##}",

totaller.AveragePrice());

}

// Initialize the book database with some test books:

static void AddBooks(BookDB bookDB)

{

bookDB.AddBook("The C Programming Language",

"Brian W. Kernighan and Dennis M. Ritchie", 19.95m,

true);

bookDB.AddBook("The Unicode Standard 2.0",

"The Unicode Consortium", 39.95m, true);

bookDB.AddBook("The MS-DOS Encyclopedia",

"Ray Duncan", 129.95m, false);

Page 178: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

178

bookDB.AddBook("Dogbert's Clues for the Clueless",

"Scott Adams", 12.00m, true);

}

}

}

int availableUnits;

if (unitsInStock == null)

{

availableUnits = 0;

}

else

{

availableUnits = (int)unitsInStock;

}

velebi

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Collections.Generic;

using System.Text;

Page 179: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

179

namespace Yield

{

class Yield

{

public static class NumberList

{

// Create an array of integers.

public static int[] ints = { 1, 2, 3, 5, 8, 13, 21,

34, 55, 89, 144, 233, 377 };

// Define a property that returns only the even

numbers.

public static IEnumerable<int> GetEven()

{

// Use yield to return the even numbers in the

list.

foreach (int i in ints)

if (i % 2 == 0)

yield return i;

}

// Define a property that returns only the even

numbers.

public static IEnumerable<int> GetOdd()

{

Page 180: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

180

// Use yield to return only the odd numbers.

foreach (int i in ints)

if (i % 2 == 1)

yield return i;

}

}

static void Main(string[] args)

{

// Display the even numbers.

Console.WriteLine("Even numbers");

foreach (int i in NumberList.GetEven())

Console.WriteLine(i);

// Display the odd numbers.

Console.WriteLine("Odd numbers");

foreach (int i in NumberList.GetOdd())

Console.WriteLine(i);

}

}

}

Page 181: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

181

gardaqmnebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// conversion.cs

using System;

struct RomanNumeral

{

public RomanNumeral(int value)

{

this.value = value;

}

// Declare a conversion from an int to a RomanNumeral. Note

the

// the use of the operator keyword. This is a conversion

// operator named RomanNumeral:

static public implicit operator RomanNumeral(int value)

{

// Note that because RomanNumeral is declared as a struct,

// calling new on the struct merely calls the constructor

// rather than allocating an object on the heap:

return new RomanNumeral(value);

}

Page 182: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

182

// Declare an explicit conversion from a RomanNumeral to an

int:

static public explicit operator int(RomanNumeral roman)

{

return roman.value;

}

// Declare an implicit conversion from a RomanNumeral to

// a string:

static public implicit operator string(RomanNumeral roman)

{

return("Conversion not yet implemented");

}

private int value;

}

class Test

{

static public void Main()

{

RomanNumeral numeral;

numeral = 10;

// Call the explicit conversion from numeral to int. Because it is

Page 183: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

183

// an explicit conversion, a cast must be used:

Console.WriteLine((int)numeral);

// Call the implicit conversion to string. Because there is no

// cast, the implicit conversion to string is the only

// conversion that is considered:

Console.WriteLine(numeral);

// Call the explicit conversion from numeral to int and

// then the explicit conversion from int to short:

short s = (short)numeral;

Console.WriteLine(s);

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// structconversion.cs

using System;

struct RomanNumeral

{

public RomanNumeral(int value)

Page 184: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

184

{

this.value = value;

}

static public implicit operator RomanNumeral(int value)

{

return new RomanNumeral(value);

}

static public implicit operator RomanNumeral(BinaryNumeral

binary)

{

return new RomanNumeral((int)binary);

}

static public explicit operator int(RomanNumeral roman)

{

return roman.value;

}

static public implicit operator string(RomanNumeral roman)

{

return("Conversion not yet implemented");

}

private int value;

}

struct BinaryNumeral

Page 185: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

185

{

public BinaryNumeral(int value)

{

this.value = value;

}

static public implicit operator BinaryNumeral(int value)

{

return new BinaryNumeral(value);

}

static public implicit operator string(BinaryNumeral binary)

{

return("Conversion not yet implemented");

}

static public explicit operator int(BinaryNumeral binary)

{

return(binary.value);

}

private int value;

}

class Test

{

static public void Main()

Page 186: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

186

{

RomanNumeral roman;

roman = 10;

BinaryNumeral binary;

// Perform a conversion from a RomanNumeral to a

// BinaryNumeral:

binary = (BinaryNumeral)(int)roman;

// Performs a conversion from a BinaryNumeral to a

RomanNumeral.

// No cast is required:

roman = binary;

Console.WriteLine((int)binary);

Console.WriteLine(binary);

}

}

operatorebis gadatvirTva

//Copyright (C) Microsoft Corporation. All rights reserved.

// dbbool.cs

using System;

public struct DBBool

Page 187: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

187

{

// The three possible DBBool values:

public static readonly DBBool dbNull = new DBBool(0);

public static readonly DBBool dbFalse = new DBBool(-1);

public static readonly DBBool dbTrue = new DBBool(1);

// Private field that stores -1, 0, 1 for dbFalse, dbNull,

dbTrue:

int value;

// Private constructor. The value parameter must be -1, 0, or

1:

DBBool(int value)

{

this.value = value;

}

// Implicit conversion from bool to DBBool. Maps true to

// DBBool.dbTrue and false to DBBool.dbFalse:

public static implicit operator DBBool(bool x)

{

return x? dbTrue: dbFalse;

}

// Explicit conversion from DBBool to bool. Throws an

// exception if the given DBBool is dbNull, otherwise returns

Page 188: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

188

// true or false:

public static explicit operator bool(DBBool x)

{

if (x.value == 0) throw new InvalidOperationException();

return x.value > 0;

}

// Equality operator. Returns dbNull if either operand is

dbNull,

// otherwise returns dbTrue or dbFalse:

public static DBBool operator ==(DBBool x, DBBool y)

{

if (x.value == 0 || y.value == 0) return dbNull;

return x.value == y.value? dbTrue: dbFalse;

}

// Inequality operator. Returns dbNull if either operand is

// dbNull, otherwise returns dbTrue or dbFalse:

public static DBBool operator !=(DBBool x, DBBool y)

{

if (x.value == 0 || y.value == 0) return dbNull;

return x.value != y.value? dbTrue: dbFalse;

}

Page 189: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

189

// Logical negation operator. Returns dbTrue if the operand is

// dbFalse, dbNull if the operand is dbNull, or dbFalse if the

// operand is dbTrue:

public static DBBool operator !(DBBool x)

{

return new DBBool(-x.value);

}

// Logical AND operator. Returns dbFalse if either operand is

// dbFalse, dbNull if either operand is dbNull, otherwise

dbTrue:

public static DBBool operator &(DBBool x, DBBool y)

{

return new DBBool(x.value < y.value? x.value: y.value);

}

// Logical OR operator. Returns dbTrue if either operand is

// dbTrue, dbNull if either operand is dbNull, otherwise

dbFalse:

public static DBBool operator |(DBBool x, DBBool y)

{

return new DBBool(x.value > y.value? x.value: y.value);

}

// Definitely true operator. Returns true if the operand is

Page 190: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

190

// dbTrue, false otherwise:

public static bool operator true(DBBool x)

{

return x.value > 0;

}

// Definitely false operator. Returns true if the operand is

// dbFalse, false otherwise:

public static bool operator false(DBBool x)

{

return x.value < 0;

}

// Overload the conversion from DBBool to string:

public static implicit operator string(DBBool x)

{

return x.value > 0 ? "dbTrue"

: x.value < 0 ? "dbFalse"

: "dbNull";

}

// Override the Object.Equals(object o) method:

public override bool Equals(object o)

{

Page 191: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

191

try

{

return (bool) (this == (DBBool) o);

}

catch

{

return false;

}

}

// Override the Object.GetHashCode() method:

public override int GetHashCode()

{

return value;

}

// Override the ToString method to convert DBBool to a string:

public override string ToString()

{

switch (value)

{

case -1:

return "DBBool.False";

case 0:

Page 192: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

192

return "DBBool.Null";

case 1:

return "DBBool.True";

default:

throw new InvalidOperationException();

}

}

}

class Test

{

static void Main()

{

DBBool a, b;

a = DBBool.dbTrue;

b = DBBool.dbNull;

Console.WriteLine( "!{0} = {1}", a, !a);

Console.WriteLine( "!{0} = {1}", b, !b);

Console.WriteLine( "{0} & {1} = {2}", a, b, a & b);

Console.WriteLine( "{0} | {1} = {2}", a, b, a | b);

// Invoke the true operator to determine the Boolean

// value of the DBBool variable:

if (b)

Page 193: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

193

Console.WriteLine("b is definitely true");

else

Console.WriteLine("b is not definitely true");

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// complex.cs

using System;

public struct Complex

{

public int real;

public int imaginary;

public Complex(int real, int imaginary)

{

this.real = real;

this.imaginary = imaginary;

}

// Declare which operator to overload (+), the types

Page 194: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

194

// that can be added (two Complex objects), and the

// return type (Complex):

public static Complex operator +(Complex c1, Complex c2)

{

return new Complex(c1.real + c2.real, c1.imaginary +

c2.imaginary);

}

// Override the ToString method to display an complex number in

the suitable format:

public override string ToString()

{

return(String.Format("{0} + {1}i", real, imaginary));

}

public static void Main()

{

Complex num1 = new Complex(2,3);

Complex num2 = new Complex(3,4);

// Add two Complex objects (num1 and num2) through the

// overloaded plus operator:

Complex sum = num1 + num2;

// Print the numbers and the sum using the overriden ToString

method:

Page 195: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

195

Console.WriteLine("First complex number: {0}",num1);

Console.WriteLine("Second complex number: {0}",num2);

Console.WriteLine("The sum of the two numbers: {0}",sum);

}

}

nul tipebi

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

class NullableOperator

{

static int? GetNullableInt()

{

return null;

}

static string GetStringValue()

{

return null;

}

Page 196: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

196

static void Main()

{

// ?? operator example.

int? x = null;

// y = x, unless x is null, in which case y = -1.

int y = x ?? -1;

Console.WriteLine("y == " + y);

// Assign i to return value of method, unless

// return value is null, in which case assign

// default value of int to i.

int i = GetNullableInt() ?? default(int);

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

// ?? also works with reference types.

string s = GetStringValue();

// Display contents of s, unless s is null,

// in which case display "Unspecified".

Console.WriteLine("s = {0}", s ?? "null");

}

}

Page 197: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

197

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

class NullableBoxing

{

static void Main()

{

int? a;

object oa;

// Assigns a to Nullable<int> (value = default(int),

hasValue = false).

a = null;

// Assigns oa to null (because x==null), not boxed "int?".

oa = a;

Console.WriteLine("Testing 'a' and 'boxed a' for

null...");

// Nullable variables can be compared to null.

if (a == null)

{

Console.WriteLine(" a == null");

}

Page 198: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

198

// Boxed nullable variables can be compared to null

// because boxing a nullable where HasValue==false

// sets the reference to null.

if (oa == null)

{

Console.WriteLine(" oa == null");

}

Console.WriteLine("Unboxing a nullable type...");

int? b = 10;

object ob = b;

// Boxed nullable types can be unboxed

int? unBoxedB = (int?)ob;

Console.WriteLine(" b={0}, unBoxedB={0}", b, unBoxedB);

// Unboxing a nullable type set to null works if

// unboxed into a nullable type.

int? unBoxedA = (int?)oa;

if (oa == null && unBoxedA == null)

{

Console.WriteLine(" a and unBoxedA are null");

}

Page 199: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

199

Console.WriteLine("Attempting to unbox into non-nullable

type...");

// Unboxing a nullable type set to null throws an

// exception if unboxed into a non-nullable type.

try

{

int unBoxedA2 = (int)oa;

}

catch (Exception e)

{

Console.WriteLine(" {0}", e.Message);

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

class NullableBasics

{

static void DisplayValue(int? num)

Page 200: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

200

{

if (num.HasValue == true)

{

Console.WriteLine("num = " + num);

}

else

{

Console.WriteLine("num = null");

}

// num.Value throws an InvalidOperationException if

num.HasValue is false

try

{

Console.WriteLine("value = {0}", num.Value);

}

catch (InvalidOperationException e)

{

Console.WriteLine(e.Message);

}

}

static void Main()

{

Page 201: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

201

DisplayValue(1);

DisplayValue(null);

}

}

biblioTekebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// FunctionClient.cs

// compile with: /reference:DigitCounter.dll;Factorial.dll

// arguments: 3 5 10

using System;

// The following using directive makes the types defined in the

Functions

// namespace available in this compilation unit:

using Functions;

class FunctionClient

{

public static void Main(string[] args)

{

Console.WriteLine("Function Client");

if ( args.Length == 0 )

{

Console.WriteLine("Usage: FunctionTest ... ");

Page 202: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

202

return;

}

for ( int i = 0; i < args.Length; i++ )

{

int num = Int32.Parse(args[i]);

Console.WriteLine(

"The Digit Count for String [{0}] is [{1}]",

args[i],

// Invoke the NumberOfDigits static method in the

// DigitCount class:

DigitCount.NumberOfDigits(args[i]));

Console.WriteLine(

"The Factorial for [{0}] is [{1}]",

num,

// Invoke the Calc static method in the Factorial

class:

Factorial.Calc(num) );

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

Page 203: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

203

// Factorial.cs

// compile with: /target:library

using System;

// Declares a namespace. You need to package your libraries

according

// to their namespace so the .NET runtime can correctly load the

classes.

namespace Functions

{

public class Factorial

{

// The "Calc" static method calculates the factorial value for the

// specified integer passed in:

public static int Calc(int i)

{

return((i <= 1) ? 1 : (i * Calc(i-1)));

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

Page 204: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

204

// DigitCounter.cs

// compile with: /target:library

using System;

// Declare the same namespace as the one in Factorial.cs. This

simply

// allows types to be added to the same namespace.

namespace Functions

{

public class DigitCount

{

// The NumberOfDigits static method calculates the number

of

// digit characters in the passed string:

public static int NumberOfDigits(string theString)

{

int count = 0;

for ( int i = 0; i < theString.Length; i++ )

{

if ( Char.IsDigit(theString[i]) )

{

count++;

}

}

return count;

Page 205: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

205

}

}

}

cxadi interfeisi

//Copyright (C) Microsoft Corporation. All rights reserved.

// explicit1.cs

interface IDimensions

{

float Length();

float Width();

}

class Box : IDimensions

{

float lengthInches;

float widthInches;

public Box(float length, float width)

{

lengthInches = length;

widthInches = width;

Page 206: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

206

}

// Explicit interface member implementation:

float IDimensions.Length()

{

return lengthInches;

}

// Explicit interface member implementation:

float IDimensions.Width()

{

return widthInches;

}

public static void Main()

{

// Declare a class instance "myBox":

Box myBox = new Box(30.0f, 20.0f);

// Declare an interface instance "myDimensions":

IDimensions myDimensions = (IDimensions) myBox;

// Print out the dimensions of the box:

/* The following commented lines would produce compilation

errors because they try to access an explicitly

implemented

interface member from a class instance:

*/

//System.Console.WriteLine("Length: {0}", myBox.Length());

Page 207: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

207

//System.Console.WriteLine("Width: {0}", myBox.Width());

/* Print out the dimensions of the box by calling the

methods

from an instance of the interface:

*/

System.Console.WriteLine("Length: {0}",

myDimensions.Length());

System.Console.WriteLine("Width: {0}",

myDimensions.Width());

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// explicit2.cs

// Declare the English units interface:

interface IEnglishDimensions

{

float Length();

float Width();

}

// Declare the metric units interface:

interface IMetricDimensions

{

float Length();

Page 208: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

208

float Width();

}

// Declare the "Box" class that implements the two interfaces:

// IEnglishDimensions and IMetricDimensions:

class Box : IEnglishDimensions, IMetricDimensions

{

float lengthInches;

float widthInches;

public Box(float length, float width)

{

lengthInches = length;

widthInches = width;

}

// Explicitly implement the members of IEnglishDimensions:

float IEnglishDimensions.Length()

{

return lengthInches;

}

float IEnglishDimensions.Width()

{

return widthInches;

}

// Explicitly implement the members of IMetricDimensions:

float IMetricDimensions.Length()

Page 209: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

209

{

return lengthInches * 2.54f;

}

float IMetricDimensions.Width()

{

return widthInches * 2.54f;

}

public static void Main()

{

// Declare a class instance "myBox":

Box myBox = new Box(30.0f, 20.0f);

// Declare an instance of the English units interface:

IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;

// Declare an instance of the metric units interface:

IMetricDimensions mDimensions = (IMetricDimensions) myBox;

// Print dimensions in English units:

System.Console.WriteLine("Length(in): {0}",

eDimensions.Length());

System.Console.WriteLine("Width (in): {0}",

eDimensions.Width());

// Print dimensions in metric units:

System.Console.WriteLine("Length(cm): {0}",

mDimensions.Length());

System.Console.WriteLine("Width (cm): {0}",

mDimensions.Width());

Page 210: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

210

}

}

xdomilebebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// events1.cs

using System;

namespace MyCollections

{

using System.Collections;

// A delegate type for hooking up change notifications.

public delegate void ChangedEventHandler(object sender,

EventArgs e);

// A class that works just like ArrayList, but sends event

// notifications whenever the list changes.

public class ListWithChangedEvent: ArrayList

{

// An event that clients can use to be notified whenever the

// elements of the list change.

public event ChangedEventHandler Changed;

Page 211: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

211

// Invoke the Changed event; called whenever list changes

protected virtual void OnChanged(EventArgs e)

{

if (Changed != null)

Changed(this, e);

}

// Override some of the methods that can change the list;

// invoke event after each

public override int Add(object value)

{

int i = base.Add(value);

OnChanged(EventArgs.Empty);

return i;

}

public override void Clear()

{

base.Clear();

OnChanged(EventArgs.Empty);

}

public override object this[int index]

{

Page 212: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

212

set

{

base[index] = value;

OnChanged(EventArgs.Empty);

}

}

}

}

namespace TestEvents

{

using MyCollections;

class EventListener

{

private ListWithChangedEvent List;

public EventListener(ListWithChangedEvent list)

{

List = list;

// Add "ListChanged" to the Changed event on "List".

List.Changed += new ChangedEventHandler(ListChanged);

}

Page 213: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

213

// This will be called whenever the list changes.

private void ListChanged(object sender, EventArgs e)

{

Console.WriteLine("This is called when the event

fires.");

}

public void Detach()

{

// Detach the event and delete the list

List.Changed -= new ChangedEventHandler(ListChanged);

List = null;

}

}

class Test

{

// Test the ListWithChangedEvent class.

public static void Main()

{

// Create a new list.

ListWithChangedEvent list = new ListWithChangedEvent();

// Create a class that listens to the list's change event.

Page 214: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

214

EventListener listener = new EventListener(list);

// Add and remove items from the list.

list.Add("item 1");

list.Clear();

listener.Detach();

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// events2.cs

using System;

namespace MyCollections

{

using System.Collections;

// A class that works just like ArrayList, but sends event

// notifications whenever the list changes:

public class ListWithChangedEvent: ArrayList

{

// An event that clients can use to be notified whenever the

// elements of the list change:

Page 215: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

215

public event EventHandler Changed;

// Invoke the Changed event; called whenever list changes:

protected virtual void OnChanged(EventArgs e)

{

if (Changed != null)

Changed(this,e);

}

// Override some of the methods that can change the list;

// invoke event after each:

public override int Add(object value)

{

int i = base.Add(value);

OnChanged(EventArgs.Empty);

return i;

}

public override void Clear()

{

base.Clear();

OnChanged(EventArgs.Empty);

}

Page 216: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

216

public override object this[int index]

{

set

{

base[index] = value;

OnChanged(EventArgs.Empty);

}

}

}

}

namespace TestEvents

{

using MyCollections;

class EventListener

{

private ListWithChangedEvent List;

public EventListener(ListWithChangedEvent list)

{

List = list;

// Add "ListChanged" to the Changed event on "List":

List.Changed += new EventHandler(ListChanged);

Page 217: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

217

}

// This will be called whenever the list changes:

private void ListChanged(object sender, EventArgs e)

{

Console.WriteLine("This is called when the event

fires.");

}

public void Detach()

{

// Detach the event and delete the list:

List.Changed -= new EventHandler(ListChanged);

List = null;

}

}

class Test

{

// Test the ListWithChangedEvent class:

public static void Main()

{

// Create a new list:

ListWithChangedEvent list = new ListWithChangedEvent();

Page 218: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

218

// Create a class that listens to the list's change event:

EventListener listener = new EventListener(list);

// Add and remove items from the list:

list.Add("item 1");

list.Clear();

listener.Detach();

}

}

}

brZanebaTa striqoni

//Copyright (C) Microsoft Corporation. All rights reserved.

// cmdline1.cs

// arguments: A B C

using System;

public class CommandLine

{

public static void Main(string[] args)

{

Page 219: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

219

// The Length property is used to obtain the length of the

array.

// Notice that Length is a read-only property:

Console.WriteLine("Number of command line parameters =

{0}",

args.Length);

for(int i = 0; i < args.Length; i++)

{

Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// cmdline2.cs

// arguments: John Paul Mary

using System;

public class CommandLine2

{

public static void Main(string[] args)

{

Page 220: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

220

Console.WriteLine("Number of command line parameters =

{0}",

args.Length);

foreach(string s in args)

{

Console.WriteLine(s);

}

}

}

koleqciebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// tokens.cs

using System;

// The System.Collections namespace is made available:

using System.Collections;

// Declare the Tokens class:

public class Tokens : IEnumerable

{

private string[] elements;

Page 221: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

221

Tokens(string source, char[] delimiters)

{

// Parse the string into tokens:

elements = source.Split(delimiters);

}

// IEnumerable Interface Implementation:

// Declaration of the GetEnumerator() method

// required by IEnumerable

public IEnumerator GetEnumerator()

{

return new TokenEnumerator(this);

}

// Inner class implements IEnumerator interface:

private class TokenEnumerator : IEnumerator

{

private int position = -1;

private Tokens t;

public TokenEnumerator(Tokens t)

{

this.t = t;

}

Page 222: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

222

// Declare the MoveNext method required by IEnumerator:

public bool MoveNext()

{

if (position < t.elements.Length - 1)

{

position++;

return true;

}

else

{

return false;

}

}

// Declare the Reset method required by IEnumerator:

public void Reset()

{

position = -1;

}

// Declare the Current property required by IEnumerator:

public object Current

{

Page 223: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

223

get

{

return t.elements[position];

}

}

}

// Test Tokens, TokenEnumerator

static void Main()

{

// Testing Tokens by breaking the string into tokens:

Tokens f = new Tokens("This is a well-done program.",

new char[] {' ','-'});

foreach (string item in f)

{

Console.WriteLine(item);

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

Page 224: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

224

// tokens2.cs

using System;

using System.Collections;

public class Tokens: IEnumerable

{

private string[] elements;

Tokens(string source, char[] delimiters)

{

elements = source.Split(delimiters);

}

// IEnumerable Interface Implementation:

public TokenEnumerator GetEnumerator() // non-IEnumerable

version

{

return new TokenEnumerator(this);

}

IEnumerator IEnumerable.GetEnumerator() // IEnumerable version

{

return (IEnumerator) new TokenEnumerator(this);

Page 225: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

225

}

// Inner class implements IEnumerator interface:

public class TokenEnumerator: IEnumerator

{

private int position = -1;

private Tokens t;

public TokenEnumerator(Tokens t)

{

this.t = t;

}

public bool MoveNext()

{

if (position < t.elements.Length - 1)

{

position++;

return true;

}

else

{

return false;

Page 226: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

226

}

}

public void Reset()

{

position = -1;

}

public string Current // non-IEnumerator version: type-safe

{

get

{

return t.elements[position];

}

}

object IEnumerator.Current // IEnumerator version: returns

object

{

get

{

return t.elements[position];

}

}

Page 227: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

227

}

// Test Tokens, TokenEnumerator

static void Main()

{

Tokens f = new Tokens("This is a well-done program.",

new char [] {' ','-'});

foreach (string item in f) // try changing string to int

{

Console.WriteLine(item);

}

}

}

pirobiTi meTodebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// tokens.cs

using System;

// The System.Collections namespace is made available:

using System.Collections;

Page 228: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

228

// Declare the Tokens class:

public class Tokens : IEnumerable

{

private string[] elements;

Tokens(string source, char[] delimiters)

{

// Parse the string into tokens:

elements = source.Split(delimiters);

}

// IEnumerable Interface Implementation:

// Declaration of the GetEnumerator() method

// required by IEnumerable

public IEnumerator GetEnumerator()

{

return new TokenEnumerator(this);

}

// Inner class implements IEnumerator interface:

private class TokenEnumerator : IEnumerator

{

private int position = -1;

private Tokens t;

Page 229: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

229

public TokenEnumerator(Tokens t)

{

this.t = t;

}

// Declare the MoveNext method required by IEnumerator:

public bool MoveNext()

{

if (position < t.elements.Length - 1)

{

position++;

return true;

}

else

{

return false;

}

}

// Declare the Reset method required by IEnumerator:

public void Reset()

{

position = -1;

Page 230: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

230

}

// Declare the Current property required by IEnumerator:

public object Current

{

get

{

return t.elements[position];

}

}

}

// Test Tokens, TokenEnumerator

static void Main()

{

// Testing Tokens by breaking the string into tokens:

Tokens f = new Tokens("This is a well-done program.",

new char[] {' ','-'});

foreach (string item in f)

{

Console.WriteLine(item);

}

}

Page 231: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

231

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// tokens2.cs

using System;

using System.Collections;

public class Tokens: IEnumerable

{

private string[] elements;

Tokens(string source, char[] delimiters)

{

elements = source.Split(delimiters);

}

// IEnumerable Interface Implementation:

public TokenEnumerator GetEnumerator() // non-IEnumerable

version

Page 232: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

232

{

return new TokenEnumerator(this);

}

IEnumerator IEnumerable.GetEnumerator() // IEnumerable version

{

return (IEnumerator) new TokenEnumerator(this);

}

// Inner class implements IEnumerator interface:

public class TokenEnumerator: IEnumerator

{

private int position = -1;

private Tokens t;

public TokenEnumerator(Tokens t)

{

this.t = t;

}

public bool MoveNext()

{

if (position < t.elements.Length - 1)

Page 233: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

233

{

position++;

return true;

}

else

{

return false;

}

}

public void Reset()

{

position = -1;

}

public string Current // non-IEnumerator version: type-safe

{

get

{

return t.elements[position];

}

}

Page 234: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

234

object IEnumerator.Current // IEnumerator version: returns

object

{

get

{

return t.elements[position];

}

}

}

// Test Tokens, TokenEnumerator

static void Main()

{

Tokens f = new Tokens("This is a well-done program.",

new char [] {' ','-'});

foreach (string item in f) // try changing string to int

{

Console.WriteLine(item);

}

}

}

xml dokumenti

Page 235: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

235

//Copyright (C) Microsoft Corporation. All rights reserved.

// XMLsample.cs

// compile with: /doc:XMLsample.xml

using System;

/// <summary>

/// Class level summary documentation goes here.</summary>

/// <remarks>

/// Longer comments can be associated with a type or member

/// through the remarks tag</remarks>

public class SomeClass

{

/// <summary>

/// Store for the name property</summary>

private string myName = null;

/// <summary>

/// The class constructor. </summary>

public SomeClass()

{

// TODO: Add Constructor Logic here

}

Page 236: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

236

/// <summary>

/// Name property </summary>

/// <value>

/// A value tag is used to describe the property value</value>

public string Name

{

get

{

if ( myName == null )

{

throw new Exception("Name is null");

}

return myName;

}

}

/// <summary>

/// Description for SomeMethod.</summary>

/// <param name="s"> Parameter description for s goes

here</param>

/// <seealso cref="String">

/// You can use the cref attribute on any tag to reference a

type or member

Page 237: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

237

/// and the compiler will check that the reference exists.

</seealso>

public void SomeMethod(string s)

{

}

/// <summary>

/// Some other method. </summary>

/// <returns>

/// Return results are described through the returns

tag.</returns>

/// <seealso cref="SomeMethod(string)">

/// Notice the use of the cref attribute to reference a

specific method </seealso>

public int SomeOtherMethod()

{

return 0;

}

/// <summary>

/// The entry point for the application.

/// </summary>

/// <param name="args"> A list of command line

arguments</param>

public static int Main(String[] args)

Page 238: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

238

{

// TODO: Add code to start application here

return 0;

}

}

versiebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// versioning.cs

// CS0114 expected

public class MyBase

{

public virtual string Meth1()

{

return "MyBase-Meth1";

}

public virtual string Meth2()

{

return "MyBase-Meth2";

}

public virtual string Meth3()

{

Page 239: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

239

return "MyBase-Meth3";

}

}

class MyDerived : MyBase

{

// Overrides the virtual method Meth1 using the override

keyword:

public override string Meth1()

{

return "MyDerived-Meth1";

}

// Explicitly hide the virtual method Meth2 using the new

// keyword:

public new string Meth2()

{

return "MyDerived-Meth2";

}

// Because no keyword is specified in the following declaration

// a warning will be issued to alert the programmer that

// the method hides the inherited member MyBase.Meth3():

public string Meth3()

{

return "MyDerived-Meth3";

Page 240: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

240

}

public static void Main()

{

MyDerived mD = new MyDerived();

MyBase mB = (MyBase) mD;

System.Console.WriteLine(mB.Meth1());

System.Console.WriteLine(mB.Meth2());

System.Console.WriteLine(mB.Meth3());

}

daucveli

//Copyright (C) Microsoft Corporation. All rights reserved.

// readfile.cs

// compile with: /unsafe

// arguments: readfile.txt

// Use the program to read and display a text file.

using System;

using System.Runtime.InteropServices;

using System.Text;

Page 241: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

241

class FileReader

{

const uint GENERIC_READ = 0x80000000;

const uint OPEN_EXISTING = 3;

IntPtr handle;

[DllImport("kernel32", SetLastError=true)]

static extern unsafe IntPtr CreateFile(

string FileName, // file name

uint DesiredAccess, // access mode

uint ShareMode, // share mode

uint SecurityAttributes, // Security Attributes

uint CreationDisposition, // how to create

uint FlagsAndAttributes, // file attributes

int hTemplateFile // handle to

template file

);

[DllImport("kernel32", SetLastError=true)]

static extern unsafe bool ReadFile(

IntPtr hFile, // handle to file

Page 242: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

242

void* pBuffer, // data buffer

int NumberOfBytesToRead, // number of bytes to read

int* pNumberOfBytesRead, // number of bytes read

int Overlapped // overlapped buffer

);

[DllImport("kernel32", SetLastError=true)]

static extern unsafe bool CloseHandle(

IntPtr hObject // handle to object

);

public bool Open(string FileName)

{

// open the existing file for reading

handle = CreateFile(

FileName,

GENERIC_READ,

0,

0,

OPEN_EXISTING,

0,

0);

Page 243: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

243

if (handle != IntPtr.Zero)

return true;

else

return false;

}

public unsafe int Read(byte[] buffer, int index, int count)

{

int n = 0;

fixed (byte* p = buffer)

{

if (!ReadFile(handle, p + index, count, &n, 0))

return 0;

}

return n;

}

public bool Close()

{

//close file handle

return CloseHandle(handle);

}

}

Page 244: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

244

class Test

{

public static int Main(string[] args)

{

if (args.Length != 1)

{

Console.WriteLine("Usage : ReadFile <FileName>");

return 1;

}

if (! System.IO.File.Exists(args[0]))

{

Console.WriteLine("File " + args[0] + " not

found.");

return 1;

}

byte[] buffer = new byte[128];

FileReader fr = new FileReader();

if (fr.Open(args[0]))

{

Page 245: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

245

// We are assuming that we are reading an ASCII

file

ASCIIEncoding Encoding = new ASCIIEncoding();

int bytesRead;

do

{

bytesRead = fr.Read(buffer, 0,

buffer.Length);

string content =

Encoding.GetString(buffer,0,bytesRead);

Console.Write("{0}", content);

}

while ( bytesRead > 0);

fr.Close();

return 0;

}

else

{

Console.WriteLine("Failed to open requested

file");

return 1;

}

}

Page 246: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

246

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// printversion.cs

// compile with: /unsafe

using System;

using System.Reflection;

using System.Runtime.InteropServices;

// Give this assembly a version number:

[assembly:AssemblyVersion("4.3.2.1")]

public class Win32Imports

{

[DllImport("version.dll")]

public static extern bool GetFileVersionInfo (string

sFileName,

int handle, int size, byte[] infoBuffer);

[DllImport("version.dll")]

public static extern int GetFileVersionInfoSize (string

sFileName,

out int handle);

// The 3rd parameter - "out string pValue" - is automatically

Page 247: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

247

// marshaled from Ansi to Unicode:

[DllImport("version.dll")]

unsafe public static extern bool VerQueryValue (byte[]

pBlock,

string pSubBlock, out string pValue, out uint len);

// This VerQueryValue overload is marked with 'unsafe'

because

// it uses a short*:

[DllImport("version.dll")]

unsafe public static extern bool VerQueryValue (byte[]

pBlock,

string pSubBlock, out short *pValue, out uint len);

}

public class C

{

// Main is marked with 'unsafe' because it uses pointers:

unsafe public static int Main ()

{

try

{

int handle = 0;

// Figure out how much version info there is:

int size =

Page 248: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

248

Win32Imports.GetFileVersionInfoSize("printversion.exe",

out handle);

if (size == 0) return -1;

byte[] buffer = new byte[size];

if

(!Win32Imports.GetFileVersionInfo("printversion.exe", handle,

size, buffer))

{

Console.WriteLine("Failed to query file

version information.");

return 1;

}

short *subBlock = null;

uint len = 0;

// Get the locale info from the version info:

if (!Win32Imports.VerQueryValue (buffer,

@"\VarFileInfo\Translation", out subBlock, out len))

{

Console.WriteLine("Failed to query version

information.");

return 1;

Page 249: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

249

}

string spv = @"\StringFileInfo\" +

subBlock[0].ToString("X4") + subBlock[1].ToString("X4") +

@"\ProductVersion";

byte *pVersion = null;

// Get the ProductVersion value for this program:

string versionInfo;

if (!Win32Imports.VerQueryValue (buffer, spv, out

versionInfo, out len))

{

Console.WriteLine("Failed to query version

information.");

return 1;

}

Console.WriteLine ("ProductVersion == {0}",

versionInfo);

}

catch (Exception e)

{

Console.WriteLine ("Caught unexpected exception "

+ e.Message);

}

Page 250: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

250

return 0;

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// fastcopy.cs

// compile with: /unsafe

using System;

class Test

{

// The unsafe keyword allows pointers to be used within

// the following method:

static unsafe void Copy(byte[] src, int srcIndex,

byte[] dst, int dstIndex, int count)

{

if (src == null || srcIndex < 0 ||

dst == null || dstIndex < 0 || count < 0)

{

throw new ArgumentException();

}

Page 251: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

251

int srcLen = src.Length;

int dstLen = dst.Length;

if (srcLen - srcIndex < count ||

dstLen - dstIndex < count)

{

throw new ArgumentException();

}

// The following fixed statement pins the location of

// the src and dst objects in memory so that they will

// not be moved by garbage collection.

fixed (byte* pSrc = src, pDst = dst)

{

byte* ps = pSrc;

byte* pd = pDst;

// Loop over the count in blocks of 4 bytes, copying

an

// integer (4 bytes) at a time:

for (int n = 0; n < count / 4; n++)

{

*((int*)pd) = *((int*)ps);

pd += 4;

Page 252: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

252

ps += 4;

}

// Complete the copy by moving any bytes that weren't

// moved in blocks of 4:

for (int n = 0; n < count % 4; n++)

{

*pd = *ps;

pd++;

ps++;

}

}

}

static void Main(string[] args)

{

byte[] a = new byte[100];

byte[] b = new byte[100];

for (int i = 0; i < 100; ++i)

a[i] = (byte)i;

Copy(a, 0, b, 0, 100);

Console.WriteLine("The first 10 elements are:");

for (int i = 0; i < 10; ++i)

Page 253: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

253

Console.Write(b[i] + " ");

Console.WriteLine("\n");

}

}

Zafebi

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Threading;

using System.Collections;

using System.Collections.Generic;

// The thread synchronization events are encapsulated in this

// class to allow them to easily be passed to the Consumer and

// Producer classes.

public class SyncEvents

{

public SyncEvents()

{

// AutoResetEvent is used for the "new item" event because

// we want this event to reset automatically each time the

Page 254: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

254

// consumer thread responds to this event.

_newItemEvent = new AutoResetEvent(false);

// ManualResetEvent is used for the "exit" event because

// we want multiple threads to respond when this event is

// signaled. If we used AutoResetEvent instead, the event

// object would revert to a non-signaled state with after

// a single thread responded, and the other thread would

// fail to terminate.

_exitThreadEvent = new ManualResetEvent(false);

// The two events are placed in a WaitHandle array as well

so

// that the consumer thread can block on both events using

// the WaitAny method.

_eventArray = new WaitHandle[2];

_eventArray[0] = _newItemEvent;

_eventArray[1] = _exitThreadEvent;

}

// Public properties allow safe access to the events.

public EventWaitHandle ExitThreadEvent

{

get { return _exitThreadEvent; }

Page 255: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

255

}

public EventWaitHandle NewItemEvent

{

get { return _newItemEvent; }

}

public WaitHandle[] EventArray

{

get { return _eventArray; }

}

private EventWaitHandle _newItemEvent;

private EventWaitHandle _exitThreadEvent;

private WaitHandle[] _eventArray;

}

// The Producer class asynchronously (using a worker thread)

// adds items to the queue until there are 20 items.

public class Producer

{

public Producer(Queue<int> q, SyncEvents e)

{

_queue = q;

_syncEvents = e;

}

Page 256: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

256

public void ThreadRun()

{

int count = 0;

Random r = new Random();

while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))

{

lock (((ICollection)_queue).SyncRoot)

{

while (_queue.Count < 20)

{

_queue.Enqueue(r.Next(0, 100));

_syncEvents.NewItemEvent.Set();

count++;

}

}

}

Console.WriteLine("Producer thread: produced {0} items",

count);

}

private Queue<int> _queue;

private SyncEvents _syncEvents;

}

// The Consumer class uses its own worker thread to consume items

Page 257: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

257

// in the queue. The Producer class notifies the Consumer class

// of new items with the NewItemEvent.

public class Consumer

{

public Consumer(Queue<int> q, SyncEvents e)

{

_queue = q;

_syncEvents = e;

}

public void ThreadRun()

{

int count = 0;

while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)

{

lock (((ICollection)_queue).SyncRoot)

{

int item = _queue.Dequeue();

}

count++;

}

Console.WriteLine("Consumer Thread: consumed {0} items",

count);

}

private Queue<int> _queue;

Page 258: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

258

private SyncEvents _syncEvents;

}

public class ThreadSyncSample

{

private static void ShowQueueContents(Queue<int> q)

{

// Enumerating a collection is inherently not thread-safe,

// so it is imperative that the collection be locked

throughout

// the enumeration to prevent the consumer and producer

threads

// from modifying the contents. (This method is called by

the

// primary thread only.)

lock (((ICollection)q).SyncRoot)

{

foreach (int i in q)

{

Console.Write("{0} ", i);

}

}

Console.WriteLine();

}

Page 259: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

259

static void Main()

{

// Configure struct containing event information required

// for thread synchronization.

SyncEvents syncEvents = new SyncEvents();

// Generic Queue collection is used to store items to be

// produced and consumed. In this case 'int' is used.

Queue<int> queue = new Queue<int>();

// Create objects, one to produce items, and one to

// consume. The queue and the thread synchronization

// events are passed to both objects.

Console.WriteLine("Configuring worker threads...");

Producer producer = new Producer(queue, syncEvents);

Consumer consumer = new Consumer(queue, syncEvents);

// Create the thread objects for producer and consumer

// objects. This step does not create or launch the

// actual threads.

Thread producerThread = new Thread(producer.ThreadRun);

Thread consumerThread = new Thread(consumer.ThreadRun);

// Create and launch both threads.

Page 260: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

260

Console.WriteLine("Launching producer and consumer

threads...");

producerThread.Start();

consumerThread.Start();

// Let producer and consumer threads run for 10 seconds.

// Use the primary thread (the thread executing this

method)

// to display the queue contents every 2.5 seconds.

for (int i = 0; i < 4; i++)

{

Thread.Sleep(2500);

ShowQueueContents(queue);

}

// Signal both consumer and producer thread to terminate.

// Both threads will respond because ExitThreadEvent is a

// manual-reset event--so it stays 'set' unless explicitly

reset.

Console.WriteLine("Signaling threads to terminate...");

syncEvents.ExitThreadEvent.Set();

// Use Join to block primary thread, first until the

producer thread

// terminates, then until the consumer thread terminates.

Page 261: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

261

Console.WriteLine("main thread waiting for threads to

finish...");

producerThread.Join();

consumerThread.Join();

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Threading;

public class Worker

{

// This method will be called when the thread is started.

public void DoWork()

{

while (!_shouldStop)

{

Console.WriteLine("worker thread: working...");

}

Console.WriteLine("worker thread: terminating

gracefully.");

}

public void RequestStop()

Page 262: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

262

{

_shouldStop = true;

}

// Volatile is used as hint to the compiler that this data

// member will be accessed by multiple threads.

private volatile bool _shouldStop;

}

public class WorkerThreadExample

{

static void Main()

{

// Create the thread object. This does not start the

thread.

Worker workerObject = new Worker();

Thread workerThread = new Thread(workerObject.DoWork);

// Start the worker thread.

workerThread.Start();

Console.WriteLine("main thread: Starting worker

thread...");

// Loop until worker thread activates.

while (!workerThread.IsAlive);

Page 263: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

263

// Put the main thread to sleep for 1 millisecond to

// allow the worker thread to do some work:

Thread.Sleep(1);

// Request that the worker thread stop itself:

workerObject.RequestStop();

// Use the Join method to block the current thread

// until the object's thread terminates.

workerThread.Join();

Console.WriteLine("main thread: Worker thread has

terminated.");

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Threading;

// The Fibonacci class provides an interface for using an

auxiliary

// thread to perform the lengthy Fibonacci(N) calculation.

// N is provided to the Fibonacci constructor, along with an

// event that the object signals when the operation is complete.

// The result can then be retrieved with the FibOfN property.

Page 264: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

264

public class Fibonacci

{

public Fibonacci(int n, ManualResetEvent doneEvent)

{

_n = n;

_doneEvent = doneEvent;

}

// Wrapper method for use with thread pool.

public void ThreadPoolCallback(Object threadContext)

{

int threadIndex = (int)threadContext;

Console.WriteLine("thread {0} started...", threadIndex);

_fibOfN = Calculate(_n);

Console.WriteLine("thread {0} result calculated...",

threadIndex);

_doneEvent.Set();

}

// Recursive method that calculates the Nth Fibonacci number.

public int Calculate(int n)

{

if (n <= 1)

{

Page 265: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

265

return n;

}

else

{

return Calculate(n - 1) + Calculate(n - 2);

}

}

public int N { get { return _n; } }

private int _n;

public int FibOfN { get { return _fibOfN; } }

private int _fibOfN;

ManualResetEvent _doneEvent;

}

public class ThreadPoolExample

{

static void Main()

{

const int FibonacciCalculations = 10;

// One event is used for each Fibonacci object

Page 266: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

266

ManualResetEvent[] doneEvents = new

ManualResetEvent[FibonacciCalculations];

Fibonacci[] fibArray = new

Fibonacci[FibonacciCalculations];

Random r = new Random();

// Configure and launch threads using ThreadPool:

Console.WriteLine("launching {0} tasks...",

FibonacciCalculations);

for (int i = 0; i < FibonacciCalculations; i++)

{

doneEvents[i] = new ManualResetEvent(false);

Fibonacci f = new Fibonacci(r.Next(20,40),

doneEvents[i]);

fibArray[i] = f;

ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);

}

// Wait for all threads in pool to calculation...

WaitHandle.WaitAll(doneEvents);

Console.WriteLine("Calculations complete.");

// Display the results...

for (int i= 0; i<FibonacciCalculations; i++)

{

Page 267: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

267

Fibonacci f = fibArray[i];

Console.WriteLine("Fibonacci({0}) = {1}", f.N,

f.FibOfN);

}

}

}

usafrTxoeba

//Copyright (C) Microsoft Corporation. All rights reserved.

// ImperativeSecurity.cs

using System;

using System.Security;

using System.Security.Permissions;

using System.Runtime.InteropServices;

class NativeMethods

{

// This is a call to unmanaged code. Executing this method

requires

// the UnmanagedCode security permission. Without this

permission

// an attempt to call this method will throw a

SecurityException:

Page 268: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

268

[DllImport("msvcrt.dll")]

public static extern int puts(string str);

[DllImport("msvcrt.dll")]

internal static extern int _flushall();

}

class MainClass

{

private static void CallUnmanagedCodeWithoutPermission()

{

// Create a security permission object to describe the

// UnmanagedCode permission:

SecurityPermission perm =

new

SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// Deny the UnmanagedCode from our current set of

permissions.

// Any method that is called on this thread until this

method

// returns will be denied access to unmanaged code.

// Even though the CallUnmanagedCodeWithPermission method

// is called from a stack frame that already

// calls Assert for unmanaged code, you still cannot call

native

Page 269: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

269

// code. Because you use Deny here, the permission gets

// overwritten.

perm.Deny();

try

{

Console.WriteLine("Attempting to call unmanaged code

without permission.");

NativeMethods.puts("Hello World!");

NativeMethods._flushall();

Console.WriteLine("Called unmanaged code without

permission. Whoops!");

}

catch (SecurityException)

{

Console.WriteLine("Caught Security Exception

attempting to call unmanaged code.");

}

}

private static void CallUnmanagedCodeWithPermission()

{

// Create a security permission object to describe the

// UnmanagedCode permission:

SecurityPermission perm =

Page 270: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

270

new

SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// Check that you have permission to access unmanaged

code.

// If you don't have permission to access unmanaged code,

then

// this call will throw a SecurityException.

// Even though the CallUnmanagedCodeWithPermission method

// is called from a stack frame that already

// calls Assert for unmanaged code, you still cannot call

native

// code. Because you use Deny here, the permission gets

// overwritten.

perm.Assert();

try

{

Console.WriteLine("Attempting to call unmanaged code

with permission.");

NativeMethods.puts("Hello World!");

NativeMethods._flushall();

Console.WriteLine("Called unmanaged code with

permission.");

}

catch (SecurityException)

Page 271: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

271

{

Console.WriteLine("Caught Security Exception

attempting to call unmanaged code. Whoops!");

}

}

public static void Main()

{

// The method itself will call the security permission

Deny

// for unmanaged code, which will override the Assert

permission

// in this stack frame.

SecurityPermission perm = new

SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

perm.Assert();

CallUnmanagedCodeWithoutPermission();

// The method itself will call the security permission

Assert

// for unmanaged code, which will override the Deny

permission in

// this stack frame.

perm.Deny();

CallUnmanagedCodeWithPermission();

Page 272: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

272

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// DeclarativeSecurity.cs

using System;

using System.Security;

using System.Security.Permissions;

using System.Runtime.InteropServices;

class NativeMethods

{

// This is a call to unmanaged code. Executing this method

requires

// the UnmanagedCode security permission. Without this

permission,

// an attempt to call this method will throw a

SecurityException:

[DllImport("msvcrt.dll")]

public static extern int puts(string str);

[DllImport("msvcrt.dll")]

internal static extern int _flushall();

}

Page 273: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

273

class MainClass

{

// The security permission attached to this method will deny

the

// UnmanagedCode permission from the current set of

permissions for

// the duration of the call to this method:

// Even though the CallUnmanagedCodeWithoutPermission method

is

// called from a stack frame that already calls

// Assert for unmanaged code, you still cannot call native

code.

// Because this function is attached with the Deny permission

for

// unmanaged code, the permission gets overwritten.

[SecurityPermission(SecurityAction.Deny, Flags =

SecurityPermissionFlag.UnmanagedCode)]

private static void CallUnmanagedCodeWithoutPermission()

{

try

{

Console.WriteLine("Attempting to call unmanaged code

without permission.");

NativeMethods.puts("Hello World!");

NativeMethods._flushall();

Page 274: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

274

Console.WriteLine("Called unmanaged code without

permission. Whoops!");

}

catch (SecurityException)

{

Console.WriteLine("Caught Security Exception

attempting to call unmanaged code.");

}

}

// The security permission attached to this method will force

a

// runtime check for the unmanaged code permission whenever

// this method is called. If the caller does not have

unmanaged code

// permission, then the call will generate a Security

Exception.

// Even though the CallUnmanagedCodeWithPermission method is

called

// from a stack frame that already calls

// Deny for unmanaged code, it will not prevent you from

calling

// native code. Because this method is attached with the

Assert

// permission for unmanaged code, the permission gets

overwritten.

[SecurityPermission(SecurityAction.Assert, Flags =

Page 275: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

275

SecurityPermissionFlag.UnmanagedCode)]

private static void CallUnmanagedCodeWithPermission()

{

try

{

Console.WriteLine("Attempting to call unmanaged code

with permission.");

NativeMethods.puts("Hello World!");

NativeMethods._flushall();

Console.WriteLine("Called unmanaged code with

permission.");

}

catch (SecurityException)

{

Console.WriteLine("Caught Security Exception

attempting to call unmanaged code. Whoops!");

}

}

public static void Main()

{

SecurityPermission perm = new

SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

Page 276: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

276

// The method itself is attached with the security

permission

// Deny for unmanaged code, which will override

// the Assert permission in this stack frame.

perm.Assert();

CallUnmanagedCodeWithoutPermission();

// The method itself is attached with the security

permission

// Assert for unmanaged code, which will override the Deny

// permission in this stack frame.

perm.Deny();

CallUnmanagedCodeWithPermission();

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// SuppressSecurity.cs

using System;

using System.Security;

using System.Security.Permissions;

using System.Runtime.InteropServices;

Page 277: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

277

class NativeMethods

{

// This is a call to unmanaged code. Executing this method

requires

// the UnmanagedCode security permission. Without this

permission,

// an attempt to call this method will throw a

SecurityException:

/* NOTE: The SuppressUnmanagedCodeSecurityAttribute disables

the

check for the UnmanagedCode permission at runtime. Be

Careful! */

[SuppressUnmanagedCodeSecurityAttribute()]

[DllImport("msvcrt.dll")]

internal static extern int puts(string str);

[SuppressUnmanagedCodeSecurityAttribute()]

[DllImport("msvcrt.dll")]

internal static extern int _flushall();

}

class MainClass

{

// The security permission attached to this method will remove

the

// UnmanagedCode permission from the current set of

permissions for

Page 278: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

278

// the duration of the call to this method.

// Even though the CallUnmanagedCodeWithoutPermission method

is

// called from a stack frame that already calls

// Assert for unmanaged code, you still cannot call native

code.

// Because this method is attached with the Deny permission

for

// unmanaged code, the permission gets overwritten. However,

because

// you are using SuppressUnmanagedCodeSecurityAttribute here,

you can

// still call the unmanaged methods successfully.

// The code should use other security checks to ensure that

you don't

// incur a security hole.

[SecurityPermission(SecurityAction.Deny, Flags =

SecurityPermissionFlag.UnmanagedCode)]

private static void CallUnmanagedCodeWithoutPermission()

{

try

{

// The UnmanagedCode security check is disbled on the

call

// below. However, the unmanaged call only displays

UI. The

Page 279: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

279

// security will be ensured by only allowing the

unmanaged

// call if there is a UI permission.

UIPermission uiPermission =

new UIPermission(PermissionState.Unrestricted);

uiPermission.Demand();

Console.WriteLine("Attempting to call unmanaged code

without UnmanagedCode permission.");

NativeMethods.puts("Hello World!");

NativeMethods._flushall();

Console.WriteLine("Called unmanaged code without

UnmanagedCode permission.");

}

catch (SecurityException)

{

Console.WriteLine("Caught Security Exception

attempting to call unmanaged code.");

}

}

// The security permission attached to this method will add

the

// UnmanagedCode permission to the current set of permissions

for the

// duration of the call to this method.

Page 280: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

280

// Even though the CallUnmanagedCodeWithPermission method is

called

// from a stack frame that already calls

// Deny for unmanaged code, it will not prevent you from

calling

// native code. Because this method is attached with the

Assert

// permission for unmanaged code, the permission gets

overwritten.

// Because you are using

SuppressUnmanagedCodeSecurityAttribute here,

// you can call the unmanaged methods successfully.

// The SuppressUnmanagedCodeSecurityAttribute will let you

succeed,

// even if you don't have a permission.

[SecurityPermission(SecurityAction.Assert, Flags =

SecurityPermissionFlag.UnmanagedCode)]

private static void CallUnmanagedCodeWithPermission()

{

try

{

Console.WriteLine("Attempting to call unmanaged code

with permission.");

NativeMethods.puts("Hello World!");

NativeMethods._flushall();

Console.WriteLine("Called unmanaged code with

permission.");

Page 281: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

281

}

catch (SecurityException)

{

Console.WriteLine("Caught Security Exception

attempting to call unmanaged code. Whoops!");

}

}

public static void Main()

{

SecurityPermission perm = new

SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// The method itself is attached with the security

permission Deny

// for unmanaged code, which will override the Assert

permission in

// this stack frame. However, because you are using

// SuppressUnmanagedCodeSecurityAttribute, you can still

call the

// unmanaged methods successfully.

// The code should use other security checks to ensure that

you

// don't incur a security hole.

perm.Assert();

Page 282: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

282

CallUnmanagedCodeWithoutPermission();

// The method itself is attached with the security

permission

// Assert for unmanaged code, which will override the Deny

// permission in this stack frame. Because you are using

// SuppressUnmanagedCodeSecurityAttribute, you can call the

// unmanaged methods successfully.

// The SuppressUnmanagedCodeSecurityAttribute will let you

succeed,

// even if you don't have a permission.

perm.Deny();

CallUnmanagedCodeWithPermission();

}

}

pinvoke

//Copyright (C) Microsoft Corporation. All rights reserved.

// Marshal.cs

using System;

using System.Runtime.InteropServices;

Page 283: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

283

class PlatformInvokeTest

{

[DllImport("msvcrt.dll")]

public static extern int puts(

[MarshalAs(UnmanagedType.LPStr)]

string m);

[DllImport("msvcrt.dll")]

internal static extern int _flushall();

public static void Main()

{

puts("Hello World!");

_flushall();

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// pinvoke.cs

// compile with: /addmodule:logfont.netmodule

// csc pinvoke.cs /addmodule:logfont.netmodule

Page 284: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

284

using System;

using System.Runtime.InteropServices;

class PlatformInvokeTest

{

[DllImport("gdi32.dll", CharSet=CharSet.Auto)]

public static extern IntPtr CreateFontIndirect(

[In, MarshalAs(UnmanagedType.LPStruct)]

LOGFONT lplf // characteristics

);

[DllImport("gdi32.dll")]

public static extern bool DeleteObject(

IntPtr handle

);

public static void Main()

{

LOGFONT lf = new LOGFONT();

lf.lfHeight = 9;

lf.lfFaceName = "Arial";

IntPtr handle = CreateFontIndirect(lf);

if (IntPtr.Zero == handle)

Page 285: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

285

{

Console.WriteLine("Can't creates a logical

font.");

}

else

{

if (IntPtr.Size == 4)

Console.WriteLine("{0:X}",

handle.ToInt32());

else

Console.WriteLine("{0:X}",

handle.ToInt64());

// delete the logical font created.

if (!DeleteObject(handle))

Console.WriteLine("Can't delete the logical

font");

}

}

}

Page 286: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

286

//Copyright (C) Microsoft Corporation. All rights reserved.

// logfont.cs

// compile with: /target:module

using System;

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]

public class LOGFONT

{

public const int LF_FACESIZE = 32;

public int lfHeight;

public int lfWidth;

public int lfEscapement;

public int lfOrientation;

public int lfWeight;

public byte lfItalic;

public byte lfUnderline;

public byte lfStrikeOut;

public byte lfCharSet;

public byte lfOutPrecision;

public byte lfClipPrecision;

public byte lfQuality;

public byte lfPitchAndFamily;

Page 287: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

287

[MarshalAs(UnmanagedType.ByValTStr, SizeConst=LF_FACESIZE)]

public string lfFaceName;

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// PInvokeTest.cs

using System;

using System.Runtime.InteropServices;

class PlatformInvokeTest

{

[DllImport("msvcrt.dll")]

public static extern int puts(string c);

[DllImport("msvcrt.dll")]

internal static extern int _flushall();

public static void Main()

{

puts("Test");

_flushall();

}

}

Page 288: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

288

kerZo tipebi

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Collections.Generic;

using System.Text;

namespace PartialClassesExample

{

class PartialClassesMain

{

static void Main(string[] args)

{

if (args.Length != 1)

{

Console.WriteLine("One argument required.");

return;

}

// CharValues is a partial class -- two of its methods

Page 289: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

289

// are defined in CharTypesPublic.cs and two are

defined

// in CharTypesPrivate.cs.

int aCount = CharValues.CountAlphabeticChars(args[0]);

int nCount = CharValues.CountNumericChars(args[0]);

Console.Write("The input argument contains {0}

alphabetic and {1} numeric characters", aCount, nCount);

}

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Collections.Generic;

using System.Text;

namespace PartialClassesExample

{

// The partial keyword allows additional methods, fields, and

// properties of this class to be defined in other .cs files.

// This file contains the public methods defined by

CharValues.

Page 290: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

290

partial class CharValues

{

public static int CountAlphabeticChars(string str)

{

int count = 0;

foreach (char ch in str)

{

// IsAlphabetic is defined in CharTypesPrivate.cs

if (IsAlphabetic(ch))

count++;

}

return count;

}

public static int CountNumericChars(string str)

{

int count = 0;

foreach (char ch in str)

{

// IsNumeric is defined in CharTypesPrivate.cs

if (IsNumeric(ch))

count++;

}

return count;

}

Page 291: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

291

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Collections.Generic;

using System.Text;

namespace PartialClassesExample

{

// The partial keyword allows additional methods, fields, and

// properties of this class to be defined in other .cs files.

// This file contains private methods defined by CharValues.

partial class CharValues

{

private static bool IsAlphabetic(char ch)

{

if (ch >= 'a' && ch <= 'z')

return true;

if (ch >= 'A' && ch <= 'Z')

return true;

Page 292: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

292

return false;

}

private static bool IsNumeric(char ch)

{

if (ch >= '0' && ch <= '9')

return true;

return false;

}

}

}

oledb

//Copyright (C) Microsoft Corporation. All rights reserved.

// OleDbSample.cs

// To build this sample from the command line, use the command:

// csc oledbsample.cs

using System;

using System.Data;

using System.Data.OleDb;

Page 293: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

293

using System.Xml.Serialization;

public class MainClass

{

public static void Main ()

{

// Set Access connection and select strings.

// The path to BugTypes.MDB must be changed if you

build the sample

// from the command line:

#if USINGPROJECTSYSTEM

string strAccessConn =

"Provider=Microsoft.Jet.OLEDB.4.0;Data

Source=..\\..\\BugTypes.MDB";

#else

string strAccessConn =

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BugTypes.MDB";

#endif

string strAccessSelect = "SELECT * FROM Categories";

// Create the dataset and add the Categories table to

it:

DataSet myDataSet = new DataSet();

OleDbConnection myAccessConn = null;

try

{

Page 294: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

294

myAccessConn = new OleDbConnection(strAccessConn);

}

catch(Exception ex)

{

Console.WriteLine("Error: Failed to create a

database connection. \n{0}", ex.Message);

return;

}

try

{

OleDbCommand myAccessCommand = new

OleDbCommand(strAccessSelect,myAccessConn);

OleDbDataAdapter myDataAdapter = new

OleDbDataAdapter(myAccessCommand);

myAccessConn.Open();

myDataAdapter.Fill(myDataSet,"Categories");

}

catch (Exception ex)

{

Console.WriteLine("Error: Failed to retrieve the

required data from the DataBase.\n{0}", ex.Message);

Page 295: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

295

return;

}

finally

{

myAccessConn.Close();

}

// A dataset can contain multiple tables, so let's get

them all

// into an array:

DataTableCollection dta = myDataSet.Tables;

foreach (DataTable dt in dta)

{

Console.WriteLine("Found data table {0}",

dt.TableName);

}

// The next two lines show two different ways you can

get the

// count of tables in a dataset:

Console.WriteLine("{0} tables in data set",

myDataSet.Tables.Count);

Console.WriteLine("{0} tables in data set", dta.Count);

// The next several lines show how to get information

on a

// specific table by name from the dataset:

Page 296: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

296

Console.WriteLine("{0} rows in Categories table",

myDataSet.Tables["Categories"].Rows.Count);

// The column info is automatically fetched from the

database, so

// we can read it here:

Console.WriteLine("{0} columns in Categories table",

myDataSet.Tables["Categories"].Columns.Count);

DataColumnCollection drc =

myDataSet.Tables["Categories"].Columns;

int i = 0;

foreach (DataColumn dc in drc)

{

// Print the column subscript, then the column's

name and its

// data type:

Console.WriteLine("Column name[{0}] is {1}, of

type {2}",i++ , dc.ColumnName, dc.DataType);

}

DataRowCollection dra =

myDataSet.Tables["Categories"].Rows;

foreach (DataRow dr in dra)

{

// Print the CategoryID as a subscript, then the

CategoryName:

Console.WriteLine("CategoryName[{0}] is {1}",

dr[0], dr[1]);

}

Page 297: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

297

}

}

indeqsirebuli Tvisebebi

//Copyright (C) Microsoft Corporation. All rights reserved.

// indexedproperty.cs

using System;

public class Document

{

// Type allowing the document to be viewed like an array of

words:

public class WordCollection

{

readonly Document document; // The containing document

internal WordCollection(Document d)

{

document = d;

}

Page 298: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

298

// Helper function -- search character array "text",

starting at

// character "begin", for word number "wordCount." Returns

false

// if there are less than wordCount words. Sets "start"

and

// length" to the position and length of the word within

text:

private bool GetWord(char[] text, int begin, int

wordCount,

out int start, out int

length)

{

int end = text.Length;

int count = 0;

int inWord = -1;

start = length = 0;

for (int i = begin; i <= end; ++i)

{

bool isLetter = i < end &&

Char.IsLetterOrDigit(text[i]);

if (inWord >= 0)

{

Page 299: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

299

if (!isLetter)

{

if (count++ == wordCount)

{

start = inWord;

length = i - inWord;

return true;

}

inWord = -1;

}

}

else

{

if (isLetter)

inWord = i;

}

}

return false;

}

// Indexer to get and set words of the containing

document:

public string this[int index]

{

Page 300: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

300

get

{

int start, length;

if (GetWord(document.TextArray, 0, index, out

start,

out

length))

return new string(document.TextArray, start,

length);

else

throw new IndexOutOfRangeException();

}

set

{

int start, length;

if (GetWord(document.TextArray, 0, index, out

start,

out

length))

{

// Replace the word at start/length with the

// string "value":

if (length == value.Length)

{

Array.Copy(value.ToCharArray(), 0,

Page 301: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

301

document.TextArray, start,

length);

}

else

{

char[] newText =

new char[document.TextArray.Length +

value.Length - length];

Array.Copy(document.TextArray, 0, newText,

0, start);

Array.Copy(value.ToCharArray(), 0,

newText,

start, value.Length);

Array.Copy(document.TextArray, start +

length,

newText, start + value.Length,

document.TextArray.Length -

start

-

length);

document.TextArray = newText;

}

}

else

throw new IndexOutOfRangeException();

}

Page 302: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

302

}

// Get the count of words in the containing document:

public int Count

{

get

{

int count = 0, start = 0, length = 0;

while (GetWord(document.TextArray, start + length,

0,

out start, out

length))

++count;

return count;

}

}

}

// Type allowing the document to be viewed like an "array"

// of characters:

public class CharacterCollection

{

readonly Document document; // The containing document

internal CharacterCollection(Document d)

Page 303: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

303

{

document = d;

}

// Indexer to get and set characters in the containing

document:

public char this[int index]

{

get

{

return document.TextArray[index];

}

set

{

document.TextArray[index] = value;

}

}

// Get the count of characters in the containing document:

public int Count

{

get

{

return document.TextArray.Length;

Page 304: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

304

}

}

}

// Because the types of the fields have indexers,

// these fields appear as "indexed properties":

public WordCollection Words;

public CharacterCollection Characters;

private char[] TextArray; // The text of the document.

public Document(string initialText)

{

TextArray = initialText.ToCharArray();

Words = new WordCollection(this);

Characters = new CharacterCollection(this);

}

public string Text

{

get

{

return new string(TextArray);

}

Page 305: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

305

}

}

class Test

{

static void Main()

{

Document d = new Document(

"peter piper picked a peck of pickled peppers. How many

pickled peppers did peter piper pick?"

);

// Change word "peter" to "penelope":

for (int i = 0; i < d.Words.Count; ++i)

{

if (d.Words[i] == "peter")

d.Words[i] = "penelope";

}

// Change character "p" to "P"

for (int i = 0; i < d.Characters.Count; ++i)

{

if (d.Characters[i] == 'p')

d.Characters[i] = 'P';

Page 306: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

306

}

Console.WriteLine(d.Text);

}

}

generics

// Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Collections;

using System.Collections.Generic;

using System.Text;

namespace Generics_CSharp

{

//Type parameter T in angle brackets.

public class MyList<T> : IEnumerable<T>

{

protected Node head;

protected Node current = null;

Page 307: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

307

// Nested type is also generic on T

protected class Node

{

public Node next;

//T as private member datatype.

private T data;

//T used in non-generic constructor.

public Node(T t)

{

next = null;

data = t;

}

public Node Next

{

get { return next; }

set { next = value; }

}

//T as return type of property.

public T Data

{

get { return data; }

set { data = value; }

}

}

Page 308: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

308

public MyList()

{

head = null;

}

//T as method parameter type.

public void AddHead(T t)

{

Node n = new Node(t);

n.Next = head;

head = n;

}

// Implement GetEnumerator to return IEnumerator<T> to

enable

// foreach iteration of our list. Note that in C# 2.0

// you are not required to implement Current and MoveNext.

// The compiler will create a class that implements

IEnumerator<T>.

public IEnumerator<T> GetEnumerator()

{

Node current = head;

while (current != null)

Page 309: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

309

{

yield return current.Data;

current = current.Next;

}

}

// We must implement this method because

// IEnumerable<T> inherits IEnumerable

IEnumerator IEnumerable.GetEnumerator()

{

return GetEnumerator();

}

}

public class SortedList<T> : MyList<T> where T :

IComparable<T>

{

// A simple, unoptimized sort algorithm that

// orders list elements from lowest to highest:

public void BubbleSort()

{

if (null == head || null == head.Next)

return;

Page 310: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

310

bool swapped;

do

{

Node previous = null;

Node current = head;

swapped = false;

while (current.next != null)

{

// Because we need to call this method, the

SortedList

// class is constrained on IEnumerable<T>

if (current.Data.CompareTo(current.next.Data)

> 0)

{

Node tmp = current.next;

current.next = current.next.next;

tmp.next = current;

if (previous == null)

{

head = tmp;

}

else

Page 311: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

311

{

previous.next = tmp;

}

previous = tmp;

swapped = true;

}

else

{

previous = current;

current = current.next;

}

}// end while

} while (swapped);

}

}

// A simple class that implements IComparable<T>

// using itself as the type argument. This is a

// common design pattern in objects that are

// stored in generic lists.

public class Person : IComparable<Person>

{

Page 312: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

312

string name;

int age;

public Person(string s, int i)

{

name = s;

age = i;

}

// This will cause list elements

// to be sorted on age values.

public int CompareTo(Person p)

{

return age - p.age;

}

public override string ToString()

{

return name + ":" + age;

}

// Must implement Equals.

public bool Equals(Person p)

{

Page 313: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

313

return (this.age == p.age);

}

}

class Generics

{

static void Main(string[] args)

{

//Declare and instantiate a new generic SortedList

class.

//Person is the type argument.

SortedList<Person> list = new SortedList<Person>();

//Create name and age values to initialize Person

objects.

string[] names = new string[] { "Franscoise", "Bill",

"Li", "Sandra", "Gunnar", "Alok", "Hiroyuki", "Maria",

"Alessandro", "Raul" };

int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108,

72, 30, 35 };

//Populate the list.

for (int x = 0; x < names.Length; x++)

{

list.AddHead(new Person(names[x], ages[x]));

}

Page 314: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

314

Console.WriteLine("Unsorted List:");

//Print out unsorted list.

foreach (Person p in list)

{

Console.WriteLine(p.ToString());

}

//Sort the list.

list.BubbleSort();

Console.WriteLine(String.Format("{0}Sorted List:",

Environment.NewLine));

//Print out sorted list.

foreach (Person p in list)

{

Console.WriteLine(p.ToString());

}

Console.WriteLine("Done");

}

}

}

Page 315: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

315

cominterop2

//Copyright (C) Microsoft Corporation. All rights reserved.

// CSharpServer.cs

// compile with: /target:library

// post-build command: regasm CSharpServer.dll

/tlb:CSharpServer.tlb

using System;

using System.Runtime.InteropServices;

namespace CSharpServer

{

// Since the .NET Framework interface and coclass have to

behave as

// COM objects, we have to give them guids.

[Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")]

public interface IManagedInterface

{

int PrintHi(string name);

}

[Guid("C6659361-1625-4746-931C-36014B146679")]

Page 316: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

316

public class InterfaceImplementation : IManagedInterface

{

public int PrintHi(string name)

{

Console.WriteLine("Hello, {0}!", name);

return 33;

}

}

}

cominterop1

//Copyright (C) Microsoft Corporation. All rights reserved.

// interop2.cs

// Compile with "csc interop2.cs"

using System;

using System.Runtime.InteropServices;

namespace QuartzTypeLib

{

// Declare IMediaControl as a COM interface which

// derives from IDispatch interface:

Page 317: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

317

[Guid("56A868B1-0AD4-11CE-B03A-0020AF0BA770"),

InterfaceType(ComInterfaceType.InterfaceIsDual)]

interface IMediaControl // Cannot list any base interfaces

here

{

// Note that IUnknown Interface members are NOT listed

here:

void Run();

void Pause();

void Stop();

void GetState( [In] int msTimeout, [Out] out int pfs);

void RenderFile(

[In, MarshalAs(UnmanagedType.BStr)] string

strFilename);

void AddSourceFilter(

[In, MarshalAs(UnmanagedType.BStr)] string

strFilename,

[Out, MarshalAs(UnmanagedType.Interface)]

out object ppUnk);

Page 318: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

318

[return: MarshalAs(UnmanagedType.Interface)]

object FilterCollection();

[return: MarshalAs(UnmanagedType.Interface)]

object RegFilterCollection();

void StopWhenReady();

}

// Declare FilgraphManager as a COM coclass:

[ComImport, Guid("E436EBB3-524F-11CE-9F53-0020AF0BA770")]

class FilgraphManager // Cannot have a base class or

// interface list here.

{

// Cannot have any members here

// NOTE that the C# compiler will add a default

constructor

// for you (no parameters).

}

}

class MainClass

{

/**********************************************************

Page 319: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

319

Abstract: This method collects the filename of an AVI to show

then creates an instance of the Quartz COM object.

To show the AVI, the program calls RenderFile and Run on

IMediaControl. Quartz uses its own thread and window to

display the AVI. The main thread blocks on a ReadLine until

the user presses ENTER.

Input Parameters: the location of the avi file it is

going to display

Returns: void

*************************************************************

/

public static void Main(string[] args)

{

// Check to see if the user passed in a filename:

if (args.Length != 1)

{

DisplayUsage();

return;

}

if (args[0] == "/?")

{

DisplayUsage();

return;

Page 320: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

320

}

String filename = args[0];

// Check to see if the file exists

if (!System.IO.File.Exists(filename))

{

Console.WriteLine("File " + filename + " not

found.");

DisplayUsage();

return;

}

// Create instance of Quartz

// (Calls CoCreateInstance(E436EBB3-524F-11CE-9F53-

0020AF0BA770,

// NULL, CLSCTX_ALL, IID_IUnknown,

// &graphManager).):

try

{

QuartzTypeLib.FilgraphManager graphManager =

new QuartzTypeLib.FilgraphManager();

// QueryInterface for the IMediaControl interface:

QuartzTypeLib.IMediaControl mc =

Page 321: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

321

(QuartzTypeLib.IMediaControl)graphManager;

// Call some methods on a COM interface.

// Pass in file to RenderFile method on COM

object.

mc.RenderFile(filename);

// Show file.

mc.Run();

}

catch(Exception ex)

{

Console.WriteLine("Unexpected COM exception: " +

ex.Message);

}

// Wait for completion.

Console.WriteLine("Press Enter to continue.");

Console.ReadLine();

}

private static void DisplayUsage()

{

// User did not provide enough parameters.

// Display usage.

Console.WriteLine("VideoPlayer: Plays AVI files.");

Page 322: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

322

Console.WriteLine("Usage: VIDEOPLAYER.EXE filename");

Console.WriteLine("where filename is the full path

and");

Console.WriteLine("file name of the AVI to display.");

}

}

//Copyright (C) Microsoft Corporation. All rights reserved.

// interop1.cs

// Build with "csc /R:QuartzTypeLib.dll interop1.cs"

using System;

class MainClass

{

/************************************************************

Abstract: This method collects the filename of an AVI to show

then creates an instance of the Quartz COM object.

To show the AVI, the program calls RenderFile and Run on

IMediaControl. Quartz uses its own thread and window to

display

the AVI.The main thread blocks on a ReadLine until the user

presses

Enter.

Page 323: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

323

Input Parameters: the location of the avi file it is

going to display

Returns: void

*************************************************************

*/

public static void Main(string[] args)

{

// Check to see if the user passed in a filename

if (args.Length != 1)

{

DisplayUsage();

return;

}

if (args[0] == "/?")

{

DisplayUsage();

return;

}

string filename = args[0];

// Check to see if the file exists

if (!System.IO.File.Exists(filename))

{

Page 324: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

324

Console.WriteLine("File " + filename + " not

found.");

DisplayUsage();

return;

}

// Create instance of Quartz

// (Calls CoCreateInstance(E436EBB3-524F-11CE-9F53-

0020AF0BA770,

// NULL, CLSCTX_ALL, IID_IUnknown, &graphManager).):

try

{

QuartzTypeLib.FilgraphManager graphManager =

new QuartzTypeLib.FilgraphManager();

// QueryInterface for the IMediaControl interface:

QuartzTypeLib.IMediaControl mc =

(QuartzTypeLib.IMediaControl)graphManager;

// Call some methods on a COM interface

// Pass in file to RenderFile method on COM

object.

mc.RenderFile(filename);

Page 325: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

325

// Show file.

mc.Run();

}

catch(Exception ex)

{

Console.WriteLine("Unexpected COM exception: " +

ex.Message);

}

// Wait for completion.

Console.WriteLine("Press Enter to continue.");

Console.ReadLine();

}

private static void DisplayUsage()

{

// User did not provide enough parameters.

// Display usage:

Console.WriteLine("VideoPlayer: Plays AVI files.");

Console.WriteLine("Usage: VIDEOPLAYER.EXE filename");

Console.WriteLine("where filename is the full path

and");

Console.WriteLine("file name of the AVI to display.");

}

}

Page 326: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

326

anonimuri delegatebi

//Copyright (C) Microsoft Corporation. All rights reserved.

using System;

using System.Collections.Generic;

using System.Text;

namespace AnonymousDelegate_Sample

{

// Define the delegate method.

delegate decimal CalculateBonus(decimal sales);

// Define an Employee type.

class Employee

{

public string name;

public decimal sales;

public decimal bonus;

public CalculateBonus calculation_algorithm;

}

Page 327: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

327

class Program

{

// This class will define two delegates that perform a

calculation.

// The first will be a named method, the second an

anonymous delegate.

// This is the named method.

// It defines one possible implementation of the Bonus

Calculation algorithm.

static decimal CalculateStandardBonus(decimal sales)

{

return sales / 10;

}

static void Main(string[] args)

{

// A value used in the calculation of the bonus.

// Note: This local variable will become a "captured

outer variable".

decimal multiplier = 2;

Page 328: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

328

// This delegate is defined as a named method.

CalculateBonus standard_bonus = new

CalculateBonus(CalculateStandardBonus);

// This delegate is anonymous - there is no named

method.

// It defines an alternative bonus calculation

algorithm.

CalculateBonus enhanced_bonus = delegate(decimal

sales) { return multiplier * sales / 10; };

// Declare some Employee objects.

Employee[] staff = new Employee[5];

// Populate the array of Employees.

for (int i = 0; i < 5; i++)

staff[i] = new Employee();

// Assign initial values to Employees.

staff[0].name = "Mr Apple";

staff[0].sales = 100;

staff[0].calculation_algorithm = standard_bonus;

staff[1].name = "Ms Banana";

Page 329: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

329

staff[1].sales = 200;

staff[1].calculation_algorithm = standard_bonus;

staff[2].name = "Mr Cherry";

staff[2].sales = 300;

staff[2].calculation_algorithm = standard_bonus;

staff[3].name = "Mr Date";

staff[3].sales = 100;

staff[3].calculation_algorithm = enhanced_bonus;

staff[4].name = "Ms Elderberry";

staff[4].sales = 250;

staff[4].calculation_algorithm = enhanced_bonus;

// Calculate bonus for all Employees

foreach (Employee person in staff)

PerformBonusCalculation(person);

// Display the details of all Employees

foreach (Employee person in staff)

DisplayPersonDetails(person);

Page 330: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

330

}

public static void PerformBonusCalculation(Employee

person)

{

// This method uses the delegate stored in the person

object

// to perform the calculation.

// Note: This method knows about the multiplier local

variable, even though

// that variable is outside the scope of this method.

// The multipler varaible is a "captured outer

variable".

person.bonus =

person.calculation_algorithm(person.sales);

}

public static void DisplayPersonDetails(Employee person)

{

Console.WriteLine(person.name);

Console.WriteLine(person.bonus);

Console.WriteLine("---------------");

}

}

}

Page 331: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

331

ÉÍÂËÉÓÖÒ-ØÀÒÈÖËი ÔÄÒÌÉÍოლოგიური სიÔყვარი

absolute address ÀÁÓÏËÖÔÖÒÉ ÌÉÓÀÌÀÒÈÉ

align ხაზზე ÂÀÓßÏÒÄÁÀ

anchor ÙÖÆÀ

assotiative array ÀÓÏÝÉÀÔÉÖÒÉ ÌÀÓÉÅÉ

autoescape ÀÅÔÏÌÀÔÖÒÉ ÀÝÉËÄÁÀ

auto load ÀÅÔÏÌÀÔÖÒÉ ÜÀÔÅÉÒÈÅÀ

batton ÙÉËÀÊÉ

broser ÁÒÏÖÆÄÒÉ

built-in functions ჩადგმული(ÜÀÛÄÍÄÁÖËÉ) ×ÖÍØÝÉÄÁÉ

bynary ÏÒÏÁÉÈÉ

call by name ÀÒÂÖÌÄÍÔÉÓ ÓÀáÄËÉÈ ÂÀÌÏÞÀáÄÁÀ

call conventions ÂÀÌÏÞÀáÄÁÉÓ ÛÄÈÀÍáÌÄÁÄÁÉ

class ÊËÀÓÉ

clickable image button ÓÖÒÀÈÆÄ ÃÀÓÀßÊÀÐÖÍÄÁÄËÉ ÙÉËÀÊÉ

coding ÊÏÃÉÒÄÁÀ

concatenation ÊÏÍÊÀÔÄÍÀÝÉÀ

cookie ÐÒÏÝÄÓÉÓ ÉÍÃÉÊÀÔÏÒÉ

data base ÌÏÍÀÝÄÌÈÀ ÁÀÆÀ

dynamic pages დინამიკური გვერდები

debuger ÂÀÌÌÀÒÈÅÄËÉ

debugging ÂÀÌÀÒÈÅÀ

default ÂÀÜÖÌÄÁÀ

default button ÂÀÜÖÌÄÁÉთ ÙÉËÀÊÉ

Page 332: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

332

directory ÃÉÒÄØÔÏÒÉÀ (ÊÀÔÀËÏÂÉ)

dumping ÒÀÉÌÄÓ ÌÚÉÓÉÄÒÉ ÌÃÂÏÌÀÒÄÏÁÉÓ ÀÌÏÁÄàÃÅÀ(ÂÀÌÏÔÀÍÀ)

dynamic pages ÃÉÍÀÌÉკÖÒÀÃ ÛÄØÌÍÉËÉ ÂÅÄÒÃÄÁÉ

environment ÂÀÒÄÌÏ

errors ÛÄÝÃÏÌÄÁÉ

file handle ×ÀÉËÉÓ ÓÀáÄËÖÒÉ

form ×ÏÒÌÀ

field ÅÄËÉ

file ×ÀÉËÉ

format ×ÏÒÌÀÔÉ

frame ჩარჩო

Gateway àÉÛÊÀÒÉ

gests book ÓÔÖÌÀÒÈÀ ßÉÂÍÉ

GMT გრინვიჩის მერიდიანიდან ÀÈÅËÉËÉ ÃÒÏÉÈÉ ÆÏÍÄÁÉ

header field ÓÀÈÀÖÒÉÓ ÅÄËÉ

host ÌÀÓÐÉÍÞÄËÉ

handler ÃÀÌÀÌÖÛÀÅÄÁÄËÉ

hardware ÔÄØÍÉÊÖÒÉ ÖÆÒÖÍÅÄËÚÏ×À

hash ÛÄÌÈáÅÄÅÉÈÉ ÌÏÍÀÝÄÌÉ

hidden field ×ÀÒÖËÉ ÅÄËÉ

key ÂÀÓÀÙÄÁÉ

keyword ÂÀÓÀÙÄÁÉ ÓÉÔÚÅÀ

line break ÓÔÒÉØÏÍÉÓ ÂÀßÚÅÄÔÀ

list ÓÉÀ

load ÜÀÔÅÉÒÈÅÀ

magic kookie ãÀÃÏØÒÖËÉ ÓÉÂÍÀËÉ

Page 333: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

333

menu ÌÄÍÉÖ

name argument ÓÀáÄËÉÀÍÉ ÀÒÂÖÌÄÍÔÉ

named parameter ÓÀáÄËÉÀÍÉ ÐÀÒÀÌÄÔÒÉ

namespace ÓÀáÄლÈÀ ÀÒÄ

object ÏÁÉÄØÔÉ

object oriented style ÏÁÉÄØÔÆÄ ÏÒÉÄÍÔÉÒÄÁÖËÉ ÓÔÉËÉ

parameter ÐÀÒÀÌÄÔÒÉ

parameters call by list ÐÀÒÀÌÄÔÒÄÁÉÓ ÓÉÉÈ ÂÀÌÏÞÀáÄÁÀ

password field ÐÀÓÐÏÒÔÉÓ ÅÄËÉ

patch ÂÆÀ

pipe ÀÒáÉ

pointer ÌÉÌÈÉÈÄÁÄËÉ

popup menu ÓÔÄÊÖÒÉ ÌÄÍÉÖ

pragmas ÌÉÌÈÉÈÄÁÄËÉ ÔÒÀÍÓËÀÔÏÒÉÓÀÈÅÉÓ

proxy – server proxy – ÓÄÒÅÄÒÉ

query შეკითხვა

query form ÛÄკითხვის ×ÏÒÌÀ

radio button ÒÀÃÉÏ ÙÉËÀÊÉ

reference ÌÉÈÉÈÄÁÀ

related checkbooxes ÃÀÊÀÅÛÉÒÄÁÖËÉ მოსანიშნი ÖãÒÄÁÉ

relative address ×ÀÒÃÏÁÉÈÉ ÌÉÓÀÌÀÒÈÉ

remote user ÛÏÒÄÖËÉ ÌÏÌáÌÀÒÄÁÄËÉ

reset button ÙÉËÀÊÉს ÀÙÃÂÄÍა

script ÓÊÒÉÐტი

scripting ÓÊÒÉÐÔÄÁÉÓ ÂÀÌÏÚÄÍÄÁÀ

Page 334: C# enazefpv.science.tsu.ge/csharp-leqciebi.pdf · 8 Aaq, Cven Main meTodSi mivuTiTeT argumenti string [] args, rac niSnavs, rom args aris string tipis masivi. misi mniSvnelobebi aiReba

334

scrolling list გასასრიალებელი ÓÉÀ

shortcats ÛÄÌÏÊËÄÁÄÁÉ

site ÓÀÉÔÉ

software ÐÒÏÂÒÀÌÖËÉ ÖÆÒÖÍÅÄËÚÏ×À

space áÀÒÅÄÆÉÓ ÍÉÛÀÍÉ

standalone checkbox სწრაფად მოსანიშნი ÖãÒÀ

submit ÃÀÃÀÓÔÖÒÄÁÀ

table ÝáÒÉËÉ

tag àÃÄ

text field ÔÄØÓÔÉÓ ÅÄËÉ

URL ÀÃÂÉËÉÓ ÌÉÈÉÈÄÁÀ ÉÍÔÄÒÍÄÔÛÉ

user ÌÏÌáÌÀÒÄÁÄËÉ

utility ÖÔÉËÉÔÀ (ÃÀÌáÌÀÒÄ ÐÒÏÂÒÀÌÀ)

variable ÝÅËÀÃÉ

web page ÅÄÁ ÂÅÄÒÃÉ

window ×ÀÍãÀÒÀ