Sunteți pe pagina 1din 87

What's New in Visual C# 2005 Microsoft Visual C# 2005 includes new features in the following areas: Language and

d Compiler

De!ugging Language and Compiler "he C# language now supports generic t#pes$ iterators$ and partial t#pes% "he latest version of the C# compiler also includes new features and options% &or more information$ see 'hat(s )ew in the C# 2%0 Language and Compiler% Code Editor "he Code Editor contains the following new features for Visual C# 2005% Code Snippets Code nippets speed the entr# of common code constructs !# providing a template #ou can fill out% nippets are stored as *ML files that can !e easil# edited and customi+ed% Code nippets ,C#Refa toring .efactoring tools can automaticall# restructure #our source code$ for e/ample$ !# promoting local varia!les to parameters or converting a !loc0 of code into a method% E/tract Method

Code Editor Development Environment Documentation and Language pecification

.eorder 2arameters !e"elopment En"ironment "he development environment includes the following enhancements for Visual C# 2005% #ntelliSense 1ntelli ense has !een enhanced with the following new features: "he completion list for List Mem!ers automaticall# appears when #ou !ac0space the cursor to a scope operator that precedes an o!3ect$ or when #ou undo the completion action% 'hen #ou write error handling code$ List Mem!ers helps #ou discover which e/ception to catch !# filtering irrelevant mem!ers from the completion list in a catch clause% 'hen #ou need to insert standardi+ed code$ 4utomatic Code 5eneration now allows #ou to prompt 1ntelli ense to insert the code for #ou% 1ntelli ense is availa!le when authoring 'e! applications% Class !esigner "he Class Designer is a new editor that graphicall# displa#s classes and t#pes$ and allows methods to !e added or modified% 1t is also possi!le to use refactoring tools from the Class !esigner window% ee Designing and Viewing Classes and "#pes% $%&e t 'est (en h "he 6!3ect "est 7ench is designed for simple o!3ect8level testing% 1t allows #ou to create an instance of an o!3ect$ and call its methods% Cli )$n e !eplo*ment Clic06nce deplo#ment allows #ou to pu!lish 'indows applications to a 'e! server or networ0 file share for simplified installation% 'ools Support for Strong Named +ssem%lies "he ,ro&e t ,roperties dialog !o/ has !een redesigned$ and now includes support for signing assem!lies% ee 2ro3ect 2roperties% Code Wi-ards "he following code wi+ards are now o!solete: C# Method 'i+ard

Encapsulate &ield E/tract 1nterface .ename .emove 2arameters

C# 1nde/er 'i+ard !o umentation and Language Spe ifi ation "he C# reference documentation has !een e/tensivel# rewritten to provide more complete information for common as well as advanced usage 9uestions that developers might encounter while creating applications in C#% "he C# Language pecification is no longer integrated into the :elp environment$ !ut is provided in two %doc files% "hese files are installed !# default under ../i rosoft Visual Studio 0." sharp.spe ifi ations.1022. % "he most

C# 2ropert# 'i+ard C# &ield 'i+ard

up8to8date versions can !e downloaded from the C# Developer Center on M D)% &or more information$ see C# Language pecification% With the release of Visual Studio 20053 the C# language has %een updated to "ersion 2403 whi h supports the following new features5 5enerics 5eneric t#pes are added to the language to ena!le programmers to achieve a high level of code reuse and enhanced performance for collection classes% 5eneric t#pes can differ onl# !# arit#% 2arameters can also !e forced to !e specific t#pes% &or more information$ see 5eneric "#pe 2arameters% 1terators 1terators ma0e it easier to dictate how a forea h loop will iterate over a collection(s contents% 2artial Classes 2artial t#pe definitions allow a single t#pe$ such as a class$ to !e split into multiple files% "he Visual tudio designer uses this feature to separate its generated code from user code% )ulla!le "#pes )ulla!le t#pes allow a varia!le to contain a value that is undefined% )ulla!le t#pes are useful when wor0ing with data!ases and other data structures that ma# contain elements that contain no specific values% 4non#mous Methods 1t is now possi!le to pass a !loc0 of code as a parameter% 4n#where a delegate is e/pected$ a code !loc0 can !e used instead: there is no need to define a new method% )amespace alias 9ualifier "he namespace alias 9ualifier , 55- provides more control over accessing namespace mem!ers% "he glo!al :: alias allows access the root namespace that ma# !e hidden !# an entit# in #our code% tatic Classes tatic classes are a safe and convenient wa# of declaring a class containing static methods that cannot !e instantiated% 1n C# version ;%2 #ou would have defined the class constructor as private to prevent the class !eing instantiated% E/ternal 4ssem!l# 4lias .eference different versions of the same component contained in the same assem!l# with this e/panded use of the e/tern 0e#word% 2ropert# 4ccessor 4ccessi!ilit# 1t is now possi!le to define different levels of accessi!ilit# for the get and set accessors on properties% Covariance and Contravariance in Delegates "he method passed to a delegate ma# now have greater fle/i!ilit# in its return t#pe and parameters% :ow to: Declare$ 1nstantiate$ and <se a Delegate Method group conversion provides a simplified s#nta/ for declaring delegates% &i/ed i+e 7uffers 1n an unsafe code !loc0$ it is now possi!le to declare fi/ed8si+e structures with em!edded arra#s% &riend 4ssem!lies 4ssem!lies can provide access to non8pu!lic t#pes to other assem!lies% 1nline warning control "he #pragma warning directive ma# !e used to disa!le and ena!le certain compiler warnings% volatile "he "olatile 0e#word can now !e applied to 1nt2tr and <1nt2tr% "he C# compiler introduces the following additions and changes for this release: =errorreport option pecifies the name and location of the %pd! file% =platform option Ena!les #ou to target 1tanium &amil# ,12&- and />? architectures% #pragma warning <sed to disa!le and ena!le individual warnings in code%

C# ,or C8 harp- is a new programming language% C# is used to write software that runs on the %)E" &ramewor0% 1n !rief$ C# ,unli0e C@@$ 2E.L$ C676L$ 2ascal$ etc%- is a language that targets one and onl# one platform% hosted !# an# operating s#stem% "his

platform is the %)E" &ramewor0% :owever$ the %)E" &ramewor0 itself is a computing platform that is designed to !e

,rogram Stru ture5 <sing Directive section 1nterface section Class section Main method section 'his is a simple C# program4 Call this program E/ample%cs% using #stemA

class MainClass B pu!lic static void Main,- B Console%'riteLine,C4 simple C# program%C-A D D "he C# Ee#words 4!stract 7#te class delegate event fi/ed if internal new override readonl# short struct tr# unsafe void as case const do e/plicit float implicit is null params ref si+eof switch t#peof ushort while !ase catch continue dou!le e/tern for in loc0 o!3ect private return stac0alloc this uint using !ool char decimal else false foreach int long operator protected s!#te static throw ulong virtual !rea0 chec0ed default enum finall# goto interface namespace out pu!lic sealed string true unchec0ed volatile

)ote :8 donFt mention as on varia!le name or user defined functions name% <sing csc%e/e$ the C# Command8Line Compiler "o create and run programs using the C# command8line compiler: Enter the program using a te/t editor% Compile the program% .un the program% Compiling the 2rogram C:GHcsc E/ample%cs

2rior to running csc%e/e$ #ou ma# need to run the !atch file vcvarsI2%!at$ which is t#picall# found in the ==2rogram &iles=Microsoft Visual tudio%)E"=VcJ=7in director#% ;% "he name of a C# program is ar!itrar# 2% 7# convention$ C# programs use the %cs file e/tension 2% Data "#pe 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% ;% Data "#pe 2% !oolean Data "#pe, I% 1nteger &amil# ?% int arra# 5% int 7o/ <n!o/ >% int Calculation J% int format L% int parse K% 1nteger format ;0% :e/adecimal ;;% long !o/ un!o/ ;2% long Calculation ;I% long cast ;?% !#te !o/ un!o/ ;5% !#te overflow ;>% ushort ;J% char ;L% Escape se9uences ;K% char arra# 20% char cast 2;% float 2oint )um!er 22% float parse 2I% float format 2?% float 25% dou!le 2>% dou!le Calculation 2J% dou!le &ormat 2L% dou!le parse 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2% 2K% I0% I;% I2% II% I?% I5% I>% IJ% IL% IK% ?0% ?;% ?2% ?I% ??% ?5% ?>% ?J% ?L% ?K% 50% 5;% 52% 5I% 5?% 55% 5>% decimal decimal Calculation decimal convert !ac0 and forth decimal format decimal parse Currenc# enum enum !ase t#pe enum format enum switch enums Definition #stem%Enum 7its 7itwise 4)D 7itwise )6" 7itwise 6. 7itwise hift *6. chec0ed unchec0ed Data "#pe Cast Convert from string Convert to string 7o/ing <n!o/ing )ulla!le )um!er format #stem Convert Varia!le 4ssignment

Commends5 'e can command the code in 2 wa#s% ;% == for single line command 2% =M M= for multi line command Varia%les and '*pes CVaria!lesC are simpl# storage locations for data% Nou can place data into them and retrieve their contents as part of a C# e/pression% "he interpretation of the data in a varia!le is controlled through C"#pesC% 14 (uild in data t*pe5 1ntegrals$ &loating 2oint$ '*pe s!#te !#te short ushort int tring$ and character Si-e 6in %its7 L L ;> ;> I2 Range 8;2L to ;2J 0 to 255 8I2J>L to I2J>J 0 to >55I5 82;?J?LI>?L to 2;?J?LI>?J

uint long ulong char

I2 >? >? ;>

0 to ?2K?K>J2K5 8K22IIJ20I>L5?JJ5L0L to K22IIJ20I>L5?JJ5L0J 0 to ;L??>J??0JIJ0K55;>;5 0 to >55I5

)ote: 1ntegral t#pes are well suited for those operations involving whole num!er calculations% "he char t#pe is the e/ception$ representing a single <nicode character% 8loating ,oint and !e imal '*pes '*pe float dou!le decimal Si-e 6in %its7 I2 >? ;2L ,re ision J digits ;58;> digits 2L82K decimal places Range ;%5 / ;08?5 to I%? / ;0IL 5%0 / ;08I2? to ;%J / ;0I0L ;%0 / ;082L to J%K / ;02L

Note5 &loating point t#pes are used when #ou need to perform operations re9uiring fractional representations% 'he string '*pe 4 string is a string of te/t characters% Nou t#picall# create a string with a string literal$ enclosed in 9uotes% 'e used the Console.WriteLine method to send output to the console%

!e laring and initiali-ing "aria%les5 S*nta9 5 :data t*pe; :"aria%le name; < "alue E/ample int /O;0A char genderOFmFA string nameOPa!cPA

+ll integers are %* default int4 $ther integer t*pes we ha"e to mention4 < Q <nsigned L Q Long <L Q unsigned long

+ll floating point num%ers are %* default dou%le4 $ther integer t*pes we ha"e to mention4 f Q float m Q decimal

for e/ample%$ float fO;2%5fA uit aO;2I<

long a2O;2I?L ulong !O ;2I<LA decimal d;O ;%2I?M

!efault "alues 5 4ll integer t#pes 4ll reference t#pes 7ool Es ape Se=uen e5 ome characters aren(t printa!le$ !ut #ou still need to use them in strings% "herefore$ C# has a special s#nta/ where characters can !e escaped to represent non8printa!le characters% i%e%$ !ac0 slash with character called escape se9uence E/ample$ Es ape Se=uen e G0 Ga G! Gf Gn Gr Gt Gv /eaning )ull$ not the same as the C# null value 7ell 7ac0space &orm &eed )ew line Carriage .eturn :ori+ontal "a! Vertical "a! 0 null false

C# $perators ;% 2% I% ?% 5% >% J% L% 4rithmetic operators .elational operators Logical operators assignment increment= decrement Conditional operator t#pe information operator 1nde/ operator ,8 @$8$M$ =$ R- , 4ssociativel# left, 4)D$6.$)6"- , 4ssociativel# left,S H SO HO - ,4ssociativel# left,@O$8O$MO$=O$O$RO - ,4ssociativel# right,@@$88- ,4ssociativel# leftT: is$ t#peof$ si+eof UV %

is : "he is operator is used to test an o!3ect to determine whether the o!3ect is a specific t#pe &or E/ample pu!lic class d B pu!lic static void Main,stringUV argsB float / O 20%0fA

D D

if ,/ is intB Console%'riteLine,C1nteger t#pe%%%C-A D else B Console%'riteLine,C6ther than floatC-A D Console%.eadLine,-A

t*peof: "he t#peof operator is used to represent runtime t#pe information a!out a class% &or e/ample pu!lic class d B pu!lic static void Main,stringUV argsB "#pe the"#pe O t#peof,int-A Console%'riteLine,the"#pe-A Console%.eadLine,-A

D D

si-eof: "he si+eof operator returns the si+e of a value t#pe$ as shown in the following code% ,Nou canFt determine the si+e of a reference t#pe%- "o use si+eof$ #our code must !e e/ecuting in the unsafe conte/t% "he unsafe 0e#word$ which #ou can appl# as a modifier to the calla!le mem!ers of a t#pe$ denotes an unsafe conte/t that e/tends from the parameter list to the end of the function% pu!lic class d B pu!lic static void Main,stringUV argsB int si+e O si+eof,float-A Console%'riteLine,si+e-A Console%.eadLine,-A D D 4"he dot operator is used to access mem!ers of a namespace$ class$ structure$ or enumeration$ as in #stem%Console%'riteLine,-% 'he is $perator Nou can handle incompati!le t#pes !# catching 1nvalidCastE/ception$ !ut there are other wa#s of handling this pro!lem$ such as the is operator% "he is operator allows #ou to determine whether an o!3ect reference can !e converted into a reference to a given class% Nou can use the is operator to test the t#pe of the o!3ect without performing a conversion% "he is operator returns true if the value on the left is not null and a cast to the class on the right$ if performed$ would complete without throwing an e/ception% 6therwise$ is returns false% if,a is 7ird! O ,7ird- aA == afe$ !ecause Ca is 7irdC returns true else Console%'riteLine,C)ot a 7irdC-A Nou can thin0 of the relationship !etween inherited classes as an Cis a 0ind ofC relationship$ as in C4 !ird is a 0ind of animal%C .eferences in the varia!le a must !e references to 4nimal o!3ects$ and ! is a 0ind of animal% 6f course$ ! is a !ird as well$ !ut a !ird is 3ust a special case of an animal% "he converse is not true% 4n animal is not a t#pe of !ird% ome animals are !irds$ !ut it is not true that all animals are !irds%

o the following e/pression can !e read as C1f a is a 0ind of !ird$C or C1f a is a !ird or a t#pe derived from !ird%C if ,a is 7ird'he as $perator Nou can use the as operator to perform conversions !etween t#pes without raising an e/ception% "he following statement performs a conversion of the reference in a to a value that references a class of t#pe 7ird$ and the runtime automaticall# chec0s to ensure that the conversion is accepta!le% ! O a as 7irdA Error :andling "he as operator differs from the cast operator in the wa# it handles errors% 1f$ in the preceding e/ample$ the reference in varia!le a cannot !e converted in a reference to an o!3ect of class 7ird$ the value null is stored in !$ and the program continues% "he as operator never raises an e/ception% Nou can rewrite the previous code as follows to displa# an error message if the conversion cannot !e performed: 7ird ! O a as 7irdA if ,! OO nullConsole%'riteLine,C)ot a !irdC-A 4lthough as never raises an e/ception$ an# attempt to access through the converted value will raise a )ull.eferenceE/ception if it is null% "herefore$ #ou should alwa#s chec0 the return value from as% >e*words 6ne of the strengths of C# is that the language offers relativel# few 0e#words% C# 0e#words represent the ver!s$ nouns$ and ad3ectives of the language% "he nouns of C# are instances of classes$ structs$ interfaces$ delegates$ and namespaces% Ver!s infer an action% "he goto$ for$ while$ and similar 0e#words have that role in C#% "he ad3ectives$ including the pu!lic$ private$ protected$ and static 0e#words$ are modifiers of the C# nouns% '*pes5 "#pes include reference t#pes$ value t#pes$ and unsafe pointers% '*pe lassifi ation

Referen e t*pe5 4 reference t#pe refers to an o!3ect created on the managed heap$ and the lifetime of the resulting o!3ect is controlled !# gar!age collection services provided !# the Common Language .untime ,CL.-% "he reference holds the location of an o!3ect created on the managed heap% .eference t#pes derive from #stem%6!3ect implicitl# and are created with the new 0e#word%

Class is .eference t#pe% 6ther reference t#pes are interfaces$ arra#s$ and delegates% .eference t#pes store the address of their data$ also 0nown as pointer$ on the stac0% "he actual data that address

refers to is stored in an area of memor# called the heap% "he runtime manages the memor# used !# the heap through a process called gar!age collection% 5ar!age collection recovers memor# periodicall# as needed !# disposing of items that are no longer referenced% (uilt?#n Referen e t*pes5 "here are a!out 2500 !uilt8in reference t#pes in %)E" &ramewor0$ Ever#thing not derived from #stem%Valuet#pe is reference t#pe$ including these 2500 or so !uilt8in reference t#pes$ from which other reference t#pes are derived Common Referen e t*pes #stem%6!3ect "he 6!3ect t#pe is the most general t#pe in the &ramewor0% Nou can convert an# t#pe to #stem%6!3ect$ and #ou can rel# on an# t#pe having %"o tring$ 5et"#pe and E9uals mem!ers inherited from this t#pe% #stem% tring "e/t Data #stem%"e/t% tring7uilder D#namic "e/t Data% #stem%4rra# arra# s#nta/% #stem%16% tream #stem%E/ception 7uffer for file $ Device and )etwor0 1=6% "his is an a!stract !ase class tas0 specific classes are derived from tream% handling s#stem and application defined e/ceptions% "as08specific E/ceptions inherit from this t#pe% String and String(uilder5? #stem% tring provides a set of mem!ers for wor0ing with te/t% tring sO W'elcome to ; oft searchPA sOs%.eplace ,WsearchP$P 1ndiaP-A Consol%'riteLine,s-A trings of t#pe #stem% tring are 1mmuta!le in %)E"% "hat means an# change to a string causes the runtime 4rra# of data% "his is the !ase class for all arra#s% 4rra# declarations use language specific

to create a new string and a!andon the old one% "hat happens invisi!l#$ and man# programmers might !e surprised to learn that the following code allocates four new strings in memor#% tring A == 6=2 == == == 'elcome 'elcome "o 'elcome "o ; oft 'elcome to ; oft 1ndia O W'elcomePA @O W"oPA @O W; oftPA @O W1ndiaPA

Consol%'riteLine, -A

6nl# the last strings has a .eference$ the other three will !e disposed of during 5ar!age Collection% 4voiding these t#pes of temporar# string helps avoid unnecessar# gar!age collection$ which improves the performance% "here are several wa#s to avoid temporar# strings% tring7uilder <se the <se the tring Class Concat$ Xoin or &ormat methods to 3oin multiple items in a single statement% tring7uilder Class to create d#namic ,Muta!le- strings%

olutions is the most fle/i!le !ecause it can span multiple statements

"he Default constructor creates a !uffer of ;> !#tes long$ which grows as needed% Nou can specif# an initial si+e and ma/imum si+e if #ou li0e% E/:8 tring7uilder ! Onew tring7uilder ,-A !%4ppend,W'elcomeP-A !%4ppend ,W"oP-A !%4ppend,W; oftP-A tring sO !%"o tring ,-A Consol%'riteLine,s-A 4nother 1mportant feature for the string class is that it overrides operators from operators the 4ddition E9ualit# 1ne9ualit# 4ssignment tring class 6verrides% @ OO YO O Xoins two strings to create a new string% .eturns "rue if the two strings have the same Contents$ &alse if the# are different content% "he inverse of the e9ualit# 6perator% Copies the content of one string into a new one% #stem%6!3ect% Lists the

"his causes strings to !ehave li0e value t#pes$ even though "he# are implemented as reference t#pes% Ver%atim Strings5 4 ver!atim string literal !egins with an Z$ which is followed !# a 9uoted string% "he contents of the 9uoted string are accepted without modification and can span two or more lines% using B pu!lic static void Main,B string s O ZC C: asdfasdf 6: (Miss( [ C: asdfasdfCA Console%'riteLine,s-A D D 6=2 C: asdfasdf 6: (Miss( [ C: asdfasdf Value '*pe5 Value t#pes are lightweight components that are placed on the stac0% Value t#pes directl# contain their value% Value t#pes are customaril# created staticall#% &or custom initiali+ation$ a value t#pe can !e constituted using the new statement% #stemA class MainClass

Value t#pe does not fa!ricate a value t#pe on the managed heap% 1t still resides on the stac0% Value t#pes derive from #stem%Value"#pe$ which is derived from #stem%6!3ect% trictl# #stem%6!3ect% #stem%Value"#pe defines a value t#pe !# rewriting most of the semantics of

2rimitives such as int$ float$ char$ and !ool are archet#pal value t#pes% 4s a primitive$ a string is a h#!rid% spea0ing$ strings are reference t#pes% :owever$ strings have some of the characteristics of a value t#pe% tructures and enumerations complete the list of value t#pes% #stem%Value"#pe$ which is derived from

Note5 Value t#pes derive from

#stem%6!3ect$ for this reason o!3ect is

generic data t#pe% i%e%$ it can hold either value t#pe or reference t#pe% (o9ing5 Converting the value t#pe to reference t#pe% @n%o9ing5 Converting the reference t#pe to value t#pe% &or e/ample$ using #stemA

pu!lic class s9 B pu!lic int s9rt,o!3ect o!B return ,int-o!M ,int-o!A D static void Main,stringUV argsB s9 s Onew s9,-A int s9rOs%s9rt,;0-A Console%'riteLine,C"he Console%.eadLine,-A

9rt is C@s9r-A

== another e/ample for !o/ing and un!o/ing int /O;0A o!3ect oA oO/A == !o/ing int #O,int-oA == un!o/ing Console%'riteLine,#-A Console%.eadLine,-A D D

/ain Entr* ,oint Main is the entr# point method for a C# application and a mem!er function of a class% 2u!lic static void Main ,string UV argsB == main !loc0 D )ote: "hat the entr# point method must !e static% )ote: When no arguments are passed3 the arg parameter is non?null %ut the arra* ount is -ero4 (lo )s 7loc0s define the scope of a t#pe$ where t#pe is a class$ struct$ or enum% 4dditionall#$ mem!ers of the t#pe are listed inside the !loc0% t#pe t#pename B == !loc0 D

Sele tion Statements 4 selection statement evaluates an e/pression to determine what code is e/ecuted ne/t% 7ased on the e/pression$ a selection statement transfers control to either the ne/t or some other statement% #f statement if,!oolean\e/pression- Bstatement\!loc0D if else statement if,!oolean\e/pressiontrue\statementA else false\statementA Ladder #f if,!oolean\e/pression;true\statementA else if,!oolean\e/pression2true\statement2A else false\statementA Nested if 1f,!oolean\e/pressionB 1f,!oolean\e/pressionB D D Swit h statement 4 switch statement$ which is a !etter solution to the preceding code$ 3umps to the switch la!el that matches a switch e/pression% switch,switch\e/pressionB case switch\la!el;: switch\statement;A !rea0A case case\la!eln: switch\statementnA !rea0A default: default\statementA !rea0A D #fA4 BotoA Leaves the switch !loc0 and 3umps directl# to a la!el of the form CSla!elnameH:C using #stemA pu!lic class sample B pu!lic static int Main, B int i O 0A repeat: == the la!el Console%'riteLine ,Ci: B0DC$i-A i@@A if ,i S ;0goto repeatA return 0A

D D E9ample5 using #stemA using #stem%Collections%5enericA using #stem%"e/tA class 2rogram B static void Main,stringUV argsB con: int a$ !$choiceA Console%'riteLine,CEnter the ;st num!erC-A a O int%2arse,Console%.eadLine,--A Console%'riteLine,CEnter the 2st num!erC-A ! O int%2arse,Console%.eadLine,--A Console%'riteLine,CEnter #our choice:C-A Console%'riteLine,C;% 4dditionC-A Console%'riteLine,C2% u!tractionC-A Console%'riteLine,C0% E/itC-A choice O int%2arse,Console%.eadLine,--A switch ,choiceB case ;: Console%'riteLine,C4ddition is :C @ ,a @ !--A !rea0A case 2: Console%'riteLine,Csu!traction is :C @ ,a 8 !--A !rea0A default: Console%'riteLine,C1nvalid optionC-A !rea0A D Console%'riteLine,CDo < want to Continue ,N=)- :C-A string ch O Console%.eadLine,-A if ,ch OO C#C ]] ch OO CNCB goto conA D D D Console%.ead,-A

'ernar* operators "he conditional operator is the sole ternar# operator in C# and is an a!!reviated if else statement% Conditional operator5 !oolean\e/pressionT truth\statement:false\statement E9ample class :ello'orld B static void Main,B int / O ;0$#O;IA int ma/A ma/ O / H # T / : #A

Console%'riteLine,CMa/imum is :C@ma/-A Console%.eadLine,-A D D

#terati"e Statement While5 "he statement_block of the while statement is e/ecuted while the boolean_expression is true% "he statement_block is e/ecuted +ero or more times% 1f the boolean_expression is initiall# false$ the statement_block is e/ecuted +ero times% while ,E/pressionB tatementA 1ncrement= decrementA D E9ample5 class 2rogram B static void Main,stringUV argsB int 9 < 0C while 69 :< 107 B Console%'riteLine,C/ :C @ /-A 9DDC D Console%.eadLine,-A D D !oA while do statement is when the statement_block needs to e/ecute once !efore the boolean_expression% "he iteration of the statement_block continues while the boolean_expression is true% do B statement\!loc0 D while ,conditional\statement-A E9ample class 2rogram B static void Main,stringUV argsB int 9 < 11C do B Console%'riteLine,C/ :C @ /-A 9DDC D while 69 :< 107C Console%.eadLine,-A D D

8or statement "he for statement is designed for structured iteration when a proper iterator is availa!le% "he for statement contains three clauses% &irst is the initiali+er\clause in which the loop iterators are declared% "he scope of an iterator is the for statement and statement\!loc0% econd is the !oolean\e/pression that must evaluate to a 7oolean t#pe% "he e/pression normall# compares the iterator to an end value% "hird$ the iterator\e/pression is e/ecuted at each iteration and is usuall# responsi!le for updating iterator values% Each clause is optional and delimited with a semicolon% "he statement\!loc0 is repeated until the !oolean\e/pression is false% "he statement\!loc0 is repeated +ero or more times% 1f the !oolean\e/pression is initiall# false$ the statement\!loc0 is e/ecuted +ero times% 'his is a for statement5 for,initiali+er\clauseA!oolean\e/pressionAiterator\e/pressionB statement\!loc0A D

+rra*5 4rra# is a collection of homogeneous element$ having the same data t#pe% C# supports single8dimensional$ multidimensional$ and 3agged arra#s% '*pes of arra*5 Single?dimensional arra#s$ sometimes called vectors$ consist of a single row% /ultidimensional arra#s are rectangular and consist of rows and columns% Eagged arra# also consists of rows and columns$ !ut is irregularl# shaped% ,arra# of arra#-

$ne dimension arra*5 +rra* !e laration5 Sdata t#peH UV Svaria!le nameHA Svaria!le nameH O new Sdata t#peHUno of elementV Blist separated !# W$PDA Sdata t#peH UV Svaria!le nameH O new Sdata t#peHUno of elementV Blist separated !# W$PD Sdata t#peH UV Svaria!le nameH O new Sdata t#peH UV Blist separated !# W$PD E9ample 1nt UV mar0sA Mar0sOnew int U5V B5>$ J>$ I?$ KL$ ?5DA 6r 1nt UV mar0s O new int U5V B5>$ J>$ I?$ KL$ ?5DA 6r 1nt UV mar0s O new int UV B5>$ J>$ I?$ KL$ ?5DA Note5 initiali+e the arra# reference using the right hand side ,.: - s#nta/ of declaring an arra# "he initiali+ation list ,ilist- contains the initial value for the elements of the arra#$ where the values are comma8delimited% "he num!er of values in the list should match the num!er of elements in the arra# e/actl# ^no more and no less% we can assign the values to individual element of an arra# !# using arra# inde/ for e/ample%$ a;U2VO?A

6r 6r

class 2rogram B intUV a; O new intUIVA

== Declaration of arra#

static void Main,stringUV argsB 2rogram p O new 2rogram,-A == 4ssigning value to arra# element Console%'riteLine,CEnter the arra# element :C-A for ,int i O 0A i S IA i@@B p%a;UiV O int%2arse,Console%.eadLine,--A D == Displa# the arra# elements Console%'riteLine,C4rra# elements are :C-A for ,int i O 0A i S IA i@@B Console%'riteLine,Ca;B0D :B;DC$ i$ p%a;UiV-A D Console%.eadLine,-A

D D

'wo dimension arra*5 +rra* !e laration5 Sdata t#peH U $ V Svaria!le nameHA Svaria!le nameH O new Sdata t#peHUrow$colV BB.ow list separated !# W$PD$Brow list separated !# W$PDDA Sdata t#peH UV Svaria!le nameH O new Sdata t#peHUrow$colV BB.ow list separated !# W$PD$Brow list separated !# W$PDDA 6r Sdata t#peH UV Svaria!le nameH O new Sdata t#peH UV Blist separated !# W$PD E9ample 1nt UV mar0sA Mar0sOnew int U2$2V BB5>$ J>$ I?$D$B;;$?2$I5D$B5?$2I$2;DA 6r 1nt UV mar0s O new int U2$2V BB5>$ J>$ I?$D$B;;$?2$I5D$B5?$2I$2;DA 6r 1nt UV mar0s O new int U % V BB5>$ J>$ I?$D$B;;$?2$I5D$B5?$2I$2;DA E9ample5 class 2rogram B static void Main,stringUV argsB intU$V a O new intUI$ IVA for ,int i O 0A i S IA i@@B for ,int 3 O 0A 3 S IA 3@@B aUi$ 3V O int%2arse,Console%.eadLine,--A D D for ,int i O 0A i S IA i@@B for ,int 3 O 0A 3 S IA 3@@B Console%'rite,aUi$3V@CGtC-A D Console%'riteLine,CGnC-A D 6r

D D

Console%.eadLine,-A

Eagged arra* "he most fre9uentl# found definition of a 3agged arra# is an arra# of arra#s % 4 3agged arra# is declared using multiple inde/ !rac0ets "he s#nta/ for declaring a 3agged arra# is similar to a multidimensional arra#% 1nstead of a single !rac0et ,Ur$cV-$ 3agged arra#s have two !rac0ets ,UrVUV-% 'hen declaring a 3agged arra#$ the num!er of columns is not specified and is omitted% "he num!er of elements in each row is set individuall#% "his is the s#nta/ of a 3agged arra#: type UVUV arrayname;A typea UVUV arrayname2Onew typebUrVUVA typea UVUV arraynameIOnew typebUrVUV BilistDA typeaUVUV arrayname?Onew typebUVUV BilistDA typeaUVUV arrayname5OBilistDA e/ample int UVUV w4rra#OB new int UV B;$2$ID$ new intUV B;$2D$ new intUV B;$2$I$?DDA

e/ample pu!lic class tarterB pu!lic static void Main,-B int UVUV 3aggedOnew int UJVUVA int countO0A for,int rowO0ArowS3agged%5etLength,0-A@@row- B Console%'rite,CGn.ow B0D:C$ row-A 3aggedUrowVOnew intUrow@;VA for,int inde/O0A inde/Srow@;A @@inde/- B @@countA 3aggedUrowVUinde/VOcountA Console%'rite,C B0DC$ count-A D D Console%'riteLine,CGnGn"otalsC-A for,int rowO0ArowS3agged%5etLength,0-A@@row- B int totalO0A for,int inde/O0A inde/S3aggedUrowV%5etLength,0-A @@inde/- B total@O3aggedUrowVUinde/VA D Console%'rite,CGn.ow B0D: B;DC$ row$ total-A D D D

8un tion5 needed% :a F G

&unction is a named part of the program that can !e invo0ed for other part of the program as often

ess spe ifier; :return t*pe; :fun tion name; 6arg13 arg2A7

8un tion ,rotot*pe 5 &unction protot#pe is nothing !ut &unction declaration Categories of fun tion5 )o parameter no return values% 'ith parameter without return values% 'ith parameter with return values%

No parameter no return "alues5 class 2rogram B pu!lic void accept,B Console%'riteLine,C'elcome "o C#C-A D static void Main,stringUV argsB 2rogram pOnew 2rogram,-A p%accept,-A Console%.ead,-A D D With parameter without return "alues5 class 2rogram B pu!lic void sum,int /$int #B Console%'riteLine,C um is :C @,/@#--A D static void Main,stringUV argsB 2rogram pOnew 2rogram,-A int a$ !A Console%'riteLine,CEnter ;st num!er :C-A a O int%2arse,Console%.eadLine,--A Console%'riteLine,CEnter 2st num!er :C-A ! O int%2arse,Console%.eadLine,--A p%sum,a$!-A Console%.ead,-A D D With parameter with return "alues5 class 2rogram B pu!lic int sum,int /$int #B return ,/@#-A D static void Main,stringUV argsB 2rogram pOnew 2rogram,-A int a$ !$ resultA Console%'riteLine,CEnter ;st num!er :C-A

a O int%2arse,Console%.eadLine,--A Console%'riteLine,CEnter 2st num!er :C-A ! O int%2arse,Console%.eadLine,--A result Op%sum,a$!-A Console%'riteLine,C"he um of 2 num!er :GtC@result-A Console%.ead,-A D D

'*pes of parameters5 ;% 2% I% ?% value parameters reference parameters output parameters params parameter

Value ,arameters5 "his is the default parameter in C#% 1f the parameter doesnFt have an# modifier it is value parameter !# default% 'hen #ou use value parameter the actual value is passed to the function which means changes made to the parameter is local to the function and is not pass !ac0 to the calling part% ,ie$ it will not affect the original valueclass 2rogram B pu!lic void displa#,int /B / O / @ 5A Console%'riteLine,Cinside displa# function:Gn value OGtC @/-A D static void Main,stringUV argsB 2rogram pOnew 2rogram,-A int aA Console%'riteLine,CEnter the num!er :C-A a O int%2arse,Console%.eadLine,--A p%displa#,a-A Console%'riteLine,Cinside main,- function:Gn value OGtC @ a-A Console%.ead,-A D

Note5 'h# we use .ef or outT "here are two reasons: ;%"o allows a method to alter the value of the arguments% 2% 4llow a method to return more than one value% Referen e ,arameters5 "he reference parameters are 1nput=6utput parameters meaning the# can !e used for passing a value to a function as well as to get !ac0 a value from a function% 'e can create a ref parameter !# preceding the parameter data t#pe with HrefI modifier% 'hen ever a ref parameter is passed a reference is passed to the function% ,ie%$ it will affect the original valueclass 2rogram B pu!lic void s9r,ref int iB i O i M iA D static void Main,stringUV argsB 2rogram pOnew 2rogram,-A int aA Console%'riteLine,CEnter the num!er :C-A a O int%2arse,Console%.eadLine,--A Console%'riteLine,C7efore Calling the &unction the value is :GtC @ a-A

p%s9r,ref a-A Console%'riteLine,C4fter Calling the &unction the value is :GtC @ a-A Console%.ead,-A D D Note5 4rguments are passed as ref must !e assigned the value prior call this is !ecause the reference parameter receives a valid values% "hus using WrefP$ #ou canFt use a method to give an initial values% $utput ,arameter5 ometime we want to use reference parameter to receive a value from a method$ !ut not pass in a value% .eference parameter must !e initiali+ing the value prior to call% "hus to use a ref parameter would re9uire giving an argument a dumm# value 3ust to satisf# this constraint% "o over come the pro!lem we use WoutP modifier% "he output parameter is used to return more than one value to the calling part% Note5 HoutP parameter is similar to a WrefP parameter with one e/ception% 1t can onl# !e used to pass a value out of method% 1t is not necessar# to give the varia!le used as an WoutP parameter an initial value prior to calling method% "he method will give the varia!le value% 1nside the method the parameter varia!le is alwa#s considered as a unassigned ie%$ it is assumed to have a initial value% 4fter call to method an out parameter will contain a value% class 2rogram B pu!lic int increase,int /$ int #$ out int i$ out int 3B i O / @ 5A 3 O # @ 5A return ,i @ 3-A D static void Main,stringUV argsB 2rogram pOnew 2rogram,-A int a O 20$ ! O 20$ c$ d$ resultA Console%'riteLine,Ca OC @ a-A Console%'riteLine,C! OC @ !-A result O p%increase,a$ !$ out c$ out d-A Console%'riteLine,Cnew a value aOC @ c-A Console%'riteLine,Cnew ! value !OC @ d-A Console%'riteLine,C4ddition is :C @ result-A Console%.eadLine,-A D D ,aram5 'e canFt overload method !ased on the param 0e#word% 'e should not out and ref in params arra#% 'e should use one params arra# per method )on params methods alwa#s ta0e periorit# over params methods%

pu!lic class c B pu!lic int add,params intUV a;B int sum O 0A for ,int i O 0A i S a;%LengthA i@@B sum O sum @ a;UiVA

D return sumA D pu!lic void sort,params intUV sorB int tempA for ,int i O 0A i S sor%LengthA i@@B for ,int 3 O i@;A 3 S sor%LengthA 3@@B if ,sorUiV H sorU3VB temp O sorUiVA sorUiV O sorU3VA sorU3V O tempA D D D Console%'riteLine,C"he sorted arra# is :C-A for ,int i O 0A i S sor%LengthA i@@B Console%'riteLine,sorUiV-A D D static void Main,stringUV argsB c cc O new c,-A intUV !; O new intU5VA Console%'riteLine,CEnter the arra# elements :C-A for ,int i O 0A i S !;%LengthA i@@B !;UiV O int%2arse,Console%.eadLine,--A D Console%'riteLine,C4ddition is C @ cc%add,!;--A cc%sort,!;-A Console%.eadLine,-A D D

,ol*morphism5 4!ilit# to ta0e more than one form% '*pes of pol*morphism ;% 2% tatic 2ol#morphism D#namic 2ol#morphism impl# it means one name in multiple form%

Stati ,ol*morphism5 "he overloaded functions are selected for invo0ing !# matching arguments$ !oth t#pe$ and num!er and therefore compiler is a!le to select the appropriate function for a particular call at compile time% "his is called CEarlier 7indingC or C tatic 7indingC or C tatic Lin0ingC$ also 0nown as Compile time pol#morphism% 14 8un tion $"erloading 8un tion $"erloading5 &unction ignature : ;% )um!er of parameter% 2% "#pe of parameter% 24 $perator $"erloading

I% 6rder of parameter% )6"E : .eturn t#pe is not a part of a function signature% Num%er of parameter5 class 2rogram B pu!lic void sum,int /B Console%'riteLine,C"he area of s9uare is :C@,/ M/--A D pu!lic void sum,int m$ int nB Console%'riteLine,C"he area of rectangle is :C @ ,m M n--A D static void Main,stringUV argsB 2rogram p O new 2rogram,-A p%sum,?0-A p%sum,20$ ;0-A Console%.eadLine,-A D D '*pe of parameter5 class 2rogram B pu!lic void sum,int /$ int #B Console%'riteLine,C"he um of 2 integer is :C@,/ @ #--A D pu!lic void sum,float m$ float nB Console%'riteLine,C"he sum of 2 float is :C @ ,m @ n--A D static void Main,stringUV argsB 2rogram p O new 2rogram,-A p%sum,20$ ?0-A p%sum,20%2f$ ;0%5f-A Console%.eadLine,-A D D $rder of parameter5 class 2rogram B pu!lic void sum,float /$ int #B Console%'riteLine,C"he um of 2 integer is :C@,/ @ #--A D pu!lic void sum,int m$ float nB Console%'riteLine,C"he sum of 2 float is :C @ ,m @ n--A D static void Main,stringUV argsB 2rogram p O new 2rogram,-A p%sum,20%If$ ?0-A p%sum,20$ ;0%5f-A Console%.eadLine,-A D D

Stati Varia%les and stati 8un tion 'e alread# 0now that each o!3ect has its own set of mem!er varia!les% ome time it is prefera!le to have one or more varia!les are common for all o!3ects% "he static varia!les are used for this purpose% tatic varia!les are declared as other varia!les of the class% <nli0e mem!er varia!les static varia!les$ onl# one the cop# of the static varia!le e/ists in the memor# for all others of that class pu!lic class cls; B == static varia!les are common for all o!3ects% we should declared as pu!lic == to access from outside the class pu!lic static int aA pu!lic static int !A pu!lic void increment,B a O a @ ;A D pu!lic void displa#,B Console%'riteLine,CaOC@a-A Console%'riteLine,C!OC @ !-A Console%.eadLine,-A D D class 2rogram B static void Main,stringUV argsB cls;%a O ;0A cls;%! O 20A cls; c; O new cls;,-A cls; c2 O new cls;,-A c;%increment,-A c2%increment,-A c;%displa#,-A D D Stati 8un tion5 tatic functions can onl# access the static varia!le % 'e use the class name to access the static function pu!lic class cls; B pu!lic static int aA pu!lic static int !A == static function can access onl# static varia!les% pu!lic static void displa#,B Console%'riteLine,CaOC@a-A Console%'riteLine,C!OC @ !-A Console%.eadLine,-A D D class 2rogram B static void Main,stringUV argsB cls;%a O ;0A cls;%! O 20A

cls;%displa#,-A D D

#nitiali-ations and in"o)e mem%er5 tatic mem!ers can !e initiali+ed in the same wa# as instance mem!ers$ !ut the#Fre alwa#s initiali+ed !efore an# of the instance mem!ers% :ereFs the e/act order of initiali+ation: ;% 2% I% ?% 4n# static fields are initiali+ed% "he static constructor is invo0ed% 4n# instance fields are initiali+ed% 4n instance constructor is invo0ed%

S ope of "aria%les5 Stati "aria%le tatic and instance varia!les are declared at the class level the# are 0nown as class varia!les% "he scope of these varia!les !egins at the place of their declaration and end #nstan e "aria%le +rra* element Value t*pe Referen e parameter $ut parameter Lo al "aria%les when the main method termination% 1nstance varia!le scope is with in the class onl# "hese are availa!le from arra# instance is created and cease to e/ists when there are no reference to that arra# instance% Value t#pe parameter will e/ists till the of the method

Stru ture5 +d"antage5

1t is a <ser Defined Data "#pe% Collection of Jeterogeneous elements%

tructures are Value "#pe%

tructure o!3ects are allocated in a memor# location called sta )% 1t is stored in a stac0 so that structure elements are retrieve is ver# fast% .emoving the structure from the stac0 is also fast% 1t is value t#pe so that need not create an o!3ect with new 0e#word 1t is useful for small data structure li0e comple/ num!er etc%$ 1f cop# the stac0 o!3ect to an another o!3ect then full content of the o!3ect is copied and stored in stac0 resulting a loss of efficienc# ,2erformance :itS*nta95 S4ccess B S4ccess S4ccess _% D Stru ture and fields5 pecifierH datat#pe Svar name;H pecifierH datat#pe Svar name2H pecifiersH struct SnameH

!isad"antage5

tructure !# default pu!lic and structure mem!ers are !# default private we(ve to e/plicitl# mention as pu!lic to access from outside% 4 struct in C# can contain fields% "hese fields can !e declared as private$ pu!lic$ internal% .emem!er that inside a struct$ we can onl# declare a field% 'e canFt initiali+e a field inside a struct% 1f we initiali+e it will show an error% :owever we can use constructor to initiali+e the structure fields%

E9ample pu!lic struct stud B pu!lic int noA pu!lic string nameA D class 2rogram B static void Main,stringUV argsB == 'e(ve to create an instance to use strucure stud s;A == 4ssign the value of structure mem!er,fields- through an instance of sturct s;%no O ;0A s;%name O C4nandCA Console%'riteLine,C)um!er :GtC@s;%no-A Console%'riteLine,C)ame :GtC @ s;%name-A Console%.eadLine,-A D D

Stru ture and onstru tors5 Constructors are methods with the same name as the structure% 1t will automaticall# invo0e when we create an o!3ect with new 0e#word% Constructors donFt have return t#pe% E/ample$ pu!lic struct stud B pu!lic int noA pu!lic string nameA pu!lic stud,int n$string namB no O nA name O namA D

class 2rogram B static void Main,stringUV argsB == when we create an o!3ect with new 0e#word default constructor invo0e and assign default to varia!les stud s;Onew stud,20$Ca!cC-A Console%'riteLine,C)um!er :GtC@s;%no-A Console%'riteLine,C)ame :GtC @ s;%name-A Console%.eadLine,-A D D tructure having the constructor with arguments% 1f not specified argument it will show an error% "his is !ecause framewor0 having default constructor without arguments% "he purpose of the default constructor is assigning the default value to its mem!ers%

'hen instantiated with a new operator$ the default constructor invo0e and assign default value% E9ample3 pu!lic struct stud B pu!lic int noA pu!lic string nameA D class 2rogram B static void Main,stringUV argsB == when we create an o!3ect with new 0e#word default constructor invo0e and assign default to varia!les stud s;Onew stud,-A Console%'riteLine,C)um!er :GtC@s;%no-A Console%'riteLine,C)ame :GtC @ s;%name-A Console%.eadLine,-A D D

Stru ture and Constru tor $"erloading C# struct can declare constrcutor$ !ut the# must ta0e parameters% 4 default constructor ,constructor without an# parameters- are alwa#s provided to initiali+e the struct fields to their default values% "he parameteri+ed constructors inside a struct can also !e overloaded% E9ample3 pu!lic struct stud B pu!lic int /$#A pu!lic stud,int i$int 3B / O iA # O 3A Console%'riteLine,C"he Console%'riteLine,C"he D pu!lic stud,int 0B / O # O 0A Console%'riteLine,C"he Console%'riteLine,C"he D D

Value of /OC @ /-A Value of #OC @ #-A

Value of /OC @ /-A Value of #OC @ #-A

class 2rogram B static void Main,stringUV argsB ==stud s; O new stud,;0$ 20-A stud s2 O new stud,50-A Console%.eadLine,-A D D Stru tre and this operator "he `thisF operator can also !e used in constructors and parameteri+ed constructors can !e chained inside a C# constructor% E9ample3 using #stemA

struct stud B int /A int #A pu!lic stud,int i$ int 3: this,i @ 3BD pu!lic stud,int iB / O # O iA D pu!lic void how*N,B Console%'riteLine,C"he field values are B0D [ B;DC$ /$ #-A D D class cls; B pu!lic static void Main,B stud ms; O new stud,;0$ 20-A ms;% how*N,-A Console%.eadLine,-A D D Stru ture and methods C# struct can also contain methods% "he methods can !e either static or non8static% )on static mem!ers can access !# using structure name% pu!lic struct stud B pu!lic int noA pu!lic string nameA pu!lic stud,int n$string namB no O nA name O namA D pu!lic void displa#,B Console%'riteLine,C)um!er :GtC @ no-A Console%'riteLine,C)ame :GtC @ name-A D D class 2rogram B static void Main,stringUV argsB stud s;Onew stud,20$Ca!cC-A ==stud s;A ==s;%no O ;0A ==s;%name O C/#+CA s;%displa#,-A Console%.eadLine,-A D D Stru ture and method o"erloading E9ample3 pu!lic struct stud B pu!lic int /$#A pu!lic void displa#,int i$int 3B / O iA

D pu!lic void displa#,int 0B / O # O 0A Console%'riteLine,C"he Value of /OC @ /-A Console%'riteLine,C"he Value of #OC @ #-A D D class 2rogram B static void Main,stringUV argsB stud s; O new stud,-A s;%displa#,;0$20-A s;%displa#,;0-A Console%.eadLine,-A D D Stru ture and Stati fields5 tatic fields can initili+e at the time of declaration of structure% pu!lic struct stud B pu!lic static int noO;0A pu!lic static string nameOCa!cCA pu!lic void displa#,B Console%'riteLine,C)um!er :GtC @ no-A Console%'riteLine,C)ame :GtC @ name-A D

# O 3A Console%'riteLine,C"he Value of /OC @ /-A Console%'riteLine,C"he Value of #OC @ #-A

class 2rogram B static void Main,stringUV argsB stud s;Onew stud,-A s;%displa#,-A Console%.eadLine,-A D D Stru ture and Stati mem%ers5 tatic methods can access onl# other static mem!ers and the# canFt invo0e !# using an o!3ect of the structure% "he# can invo0e onl# !# using the struct name% pu!lic struct stud B pu!lic static int no;O;0A pu!lic static int no2O20A pu!lic static void sum,B Console%'riteLine,C"he 4ddition is :GtC @ ,no; @ no2--A D

class 2rogram B

static void Main,stringUV argsB stud%sum,-A Console%.eadLine,-A D

Stru tor and propert* pu!lic struct stud B private int /A pu!lic int * B get B return /A D set B / O valueA D D D class 2rogram B static void Main,stringUV argsB stud s; O new stud,-A s;%* O 20A Console%'riteLine,C"he value of * :C@s;%*-A Console%.eadLine,-A D D Stru ture and #nterfa es "here is no inheritance for structure$ to overcome the pro!lem we go for interface% 4n interface is an function protot#pe the class or structure can inherit and give the implementation to the interface function% E/ample$ interface i; B void displa#;,-A D interface i2 B void displa#2,-A D pu!lic struct stud:i; B pu!lic void displa#;,B Console%'riteLine,C1nterface i; C-A D pu!lic void displa#2,B Console%'riteLine,C1nterface i2 C-A D

class 2rogram B

static void Main,stringUV argsB stud s; O new stud,-A s;%displa#;,-A s;%displa#2,-A Console%.eadLine,-A D

Summar*5 4ccess Modifier ,6ptional Stru ture (* default ,u%li 4 6ther modifiers are not allowed% ,2u!lic onl# allowed tructures are implicitl# sealed% "herefore we canFt inherit%

/em%ers of the stru ture %* default ,ri"ate4 tructure Mem!er can !e 2u!lic$ private$ internal% tatic mem!er$ static methods are allowed in structure% Stru ture /em%ers are5 method$ field$ properties$ inde/ers$ operator method$ Constructor$ events$ and structure% tructure Mem!ers are not spe ified with a%stra t3 "irtual3 new3 prote ted3 prote ted #nternal4 Ja"ing the onstru tor with arguments % 1f not specified argument it will show an error% "his is !ecause framewor0 having default constructor without arguments% "he purpose of the default constructor is assigning the default value to its mem!ers% 'hen instantiated with a new operator$ the default constructor invo0e and assign default value% tructure o!3ects are creating without new operator% 7ut o!3ect canFt !e used until the fields are initiali+ed%

Stru ture ha"ing the fields3 %ut initiali-e is not allowed4 Constructors are used to initiali+e the values% Stati fields3 whi h an %e initiali-e with in the stru ture % tatic methods can access onl# the static mem!ers and it can invo0e onl# !# the structure name%

Either function or constructor overloading are allowed in structure% , hould have a args 1f more than one constructor are there we can pass arguments using this from constructor% !estru tors are not allowed4 tructure canFt inherit from another structure or class%

4ll class and structure derived form o%&e t class% "his is the !ase class for all class in C# 1t is possi!le to override the method of the o!3ect class inside the structure using o"erride 0e#word tructure allow to implements interface% 'e can achieve inheritance through interface% tructure cannot contain e/plicit parameter less constructors% their default values% 4 structure cannot have an initiali+er in the form: !ase ,argument8list-% tructure mem!ers are automaticall# initiali+ed to

enum (C# Reference)


"he enum 0e#word is used to declare an enumeration$ a distinct t#pe that consists of a set of named constants called the enumerator list% <suall# it is !est to define an enum directl# within a namespace so that all classes in the namespace can access it with e9ual convenience% :owever$ an enum can also !e nested within a class or struct%

7# default$ the first enumerator has the value 0$ and the value of each successive enumerator is increased !# ;% &or e/ample enum Da#s B at$ 1n this enumeration$ values% &or e/ample: enum Da#s B atO;$ un$ Mon$ "ue$ 'ed$ "hu$ &riDA 1n this enumeration$ the se9uence of elements is forced to start from ; instead of 0% :owever$ we strongl# recommend that an enum contain a constant with a value of 0% &or more information$ see Enumeration "#pes ,C# 2rogramming 5uide-% Ever# enumeration t#pe has an underl#ing t#pe$ which can !e an# integral t#pe e/cept char% "he default underl#ing t#pe of the enumeration elements is int% "o declare an enum of another integral t#pe$ such as !#te$ use a colon after the identifier followed !# the t#pe: enum Da#s : !#te B atO;$ un$ Mon$ "ue$ 'ed$ "hu$ &riDA "he approved t#pes for an enum are %*te$ s!#te$ short$ ushort$ int$ uint$ long$ or ulong% 4 varia!le of t#pe Da#s can !e assigned an# value in the range of the underl#ing t#peA the values are not limited to the named constants% "he default value of an enum E is the value produced !# the e/pression ,E-0% Note5 4n enumerator ma# not contain white space in its name% "he underl#ing t#pe specifies how much storage is allocated for each enumerator% :owever$ an e/plicit cast is necessar# to convert from enum t#pe to an integral t#pe% &or e/ample$ the following statement assigns the enumerator un to a varia!le of the t#pe int !# using a cast to convert from enum to int: #stem%&lags4ttri!ute to an enumeration that contains some elements com!ined with a !itwise $R int / O ,int-Da#s% unA 'hen #ou appl# operation$ #ou will notice that the attri!ute affects the !ehavior of the enum when it is used with some tools% Nou can notice these changes when #ou use tools such as the Console class methods$ the E/pression Evaluator$ and so forth% .o!ust 2rogramming Xust as with an# constant$ all references to the individual values of an enum are converted to numeric literals at compile time% "his can create potential versioning issues as descri!ed in Constants ,C# 2rogramming 5uide-% 4ssigning additional values to new versions of enums$ or changing the values of the enum mem!ers in a new version$ can cause pro!lems for dependant source code% Enum values are used often in switch statements% 1f additional elements have !een added to the enum t#pe$ the test for default values can return true une/pectedl#% 1f other developers will !e using #our code$ #ou should provide guidelines a!out how their code should react if new elements are added to an# enum t#pes% E/ample 1n this e/ample$ an enumeration$ Da#s$ is declared% "wo enumerators are e/plicitl# converted to integer and assigned to integer varia!les% E/8; == 0e#word\enum%cs == enum initiali+ation: using B enum Da#s B atO;$ un$ Mon$ "ue$ 'ed$ "hu$ &riDA #stemA pu!lic class Enum"est un$ Mon$ "ue$ 'ed$ "hu$ &riDA at is 0$ un is ;$ Mon is 2$ and so forth% Enumerators can have initiali+ers to override the default

static void Main,B int / O ,int-Da#s% unA int # O ,int-Da#s%&riA Console%'riteLine,C un O B0DC$ /-A Console%'riteLine,C&ri O B0DC$ #-A D D E/82 == 0e#word\enum2%cs == <sing long enumerators using B enum .ange :long BMa/ O 2;?J?LI>?LL$ Min O 255LDA static void Main,B long / O ,long-.ange%Ma/A long # O ,long-.ange%MinA Console%'riteLine,CMa/ O B0DC$ /-A Console%'riteLine,CMin O B0DC$ #-A D D #stemA pu!lic class Enum"est

Class5 1t is a collection of different 0inds of varia!les and methods% Classes are reference t#pe% Class o!3ects are allocated in a memor# location called heap% Class is collection of data and functions$ ie%$ !inding the data and function in a single unit and access the data using the function% 7# default all class mem!ers are private% S*nta95 S4ccess B S4ccess S4ccess S4ccess D 4ccessi!ilit# is the visi!ilit# of the class and class mem!er% pecifierH datat#pe Svar name;H pecifierH datat#pe Svar name2H _% pecifierH Sreturn t#peHmethod; SparametersH _% pecifiersH class SnameH

+ + essi%ilit* !es ription

ess Spe ifiers

internal

Visi!le in containing assem!l#

internal!protected Visi!le in containing assem!l# or derived class of the current class private protected public Class /odifier 5 Modifiers are used to declarations of t#pes of mem!ers of class or structure% Visi!le inside current class Visi!le inside current class and an# derived class Visi!le in containing assem!l# and assem!lies referencing that assem!l#

/odifier Abstract Sealed static Unsa e

!es ription Class is a!stractA future instances of the class cannot !e created% Class cannot !e inherited and refined in a derived class% Class contains onl# static mem!ers% Class can contain unsafe constructs$ such as a pointerA re9uires the unsafe compiler option%

4ccess specifier is optional$ !# default private protected and private are not allowed to declare class% Class mem!ers are !# default private$ Class mem!er can !e 2u!lic$ 2rivate$ 2rotected$ 2rotected 1nternal% Class mem!er can !e 2u!lic$ 2rivate$ 2rotected$ 2rotected 1nternal% tatic mem!er$ methods are allowed% Class mem!ers are:

/em%er Classes Constants Constructor Delegate Destructor )ested classes 1nvaria!le data mem!ers

!es ription

peciali+ed methods that initiali+es a component or class for static constructors "#pe8safe containers of one or more function pointers peciali+ed method that performs cleanup of o!3ect resources upon gar!age collection

/em%er Events &ields 1nde/er 1nterfaces Method 6perators 2roperties tructures

!es ription Call!ac0s to methods provided !# a su!scri!er Data mem!ers peciali+ed propert# that inde/es the current o!3ect )ested interface .eusa!le code se9uence 6perator mem!er functions that override implicit operator !ehavior 5et and set functions presented as a field )ested structure within a class

/em%er /odifiers Modifiers refine the definition of the applica!le mem!er% Modifiers are optional and there are no defaults% ome modifiers are reserved for classification of mem!ers% &or e/ample$ the override modifier is applica!le to mem!er functions$ not data mem!ers% Lists the availa!le modifiers%

/odifier abstract "xtern #ew

!es ription 4 mem!er function has no implementation and is descri!ed through inheritance% 1mplemented in a foreign d#namic8lin0 li!rar# ,DLL-% :ides a similar mem!er or mem!ers in the !ase class%

$verride 1ndicates that a function in a derived class overrides a virtual method in the !ase class% %eadonly .ead8onl# fields are initiali+ed at declaration or in a constructor% Sealed Static &irtual &olatile $%&e t5 "he mem!er function cannot !e further refined through inheritance% Mem!er !elongs to a class and not an instance% Virtual functions are overrida!le in a derived class% Volatile fields are modifia!le !# the environment$ a separate thread$ or hardware%

6!3ects are an instance ,e/ample- of the class% Each o!3ect as its own set of mem!er$ mem!er varia!les we can access the particular mem!er of the class using the dot ,%- operator pu!lic class cls; B == class mem!ers are private !# default% we can(t access from out side of class == we can call the private mem!ers !# using pu!lic methods of the class% int aA int !A pu!lic void accept,B a O int%2arse,Console%.eadLine,--A ! O int%2arse,Console%.eadLine,--A D pu!lic void displa#,B Console%'riteLine,CaOC@a-A Console%'riteLine,C!OC @ !-A Console%.eadLine,-A D

D class 2rogram B static void Main,stringUV argsB cls; c; O new cls;,-A c;%accept,-A c;%displa#,-A D D

Constant5 1t specifies that the value of the local varia!le or filed cannot !e modified% S*nta95 :/odifier; onst :t*pe; :name;<:"alue;C H/odifierI is optional new3 pu%li 3 pri"ate3 prote ted3 internal are allowed% H onstI is 0e#word to declare the const% Wt*peI ma# one of the t#pe li0e !#te$ char$ short$ int$ float$ dou!le$ decimal$ !ool$ string$ enum t#pe$ or reference t#pe Const is used to declare the field or local varia!le that canFt !e changed during the program e/ecution% Constant Varia!les must !e given initial values when the# are declared% Constant field is a compile time constant% Constant field should not !e with a static modifier%

Read $nl*5 S*nta95 :modifier; readonl* :name; < :"alue; HmodifierI 1t ma# !e a pu!lic$ private$ protected$ internal or static% Hreadonl*I is a 0e#word to declare the readonl# varia!le $propert# or method HnameI name of the readonl# mem!er% H"alueI 1t is optional% 'e ma# give at declaration or using constructors% 'here as .ead onl# field can !e initiali+e either at the declaration or in the constructor used% "herefore read onl# field can have different value depending on the constructor used% .ead onl# can !e used for runtime constant%

/ethods Methods are the most common function mem!er% Methods accept parameters as input$ perform an operation$ and return the result of the operation% 7oth parameters and the return result are optional% Methods are descri!ed through the method header$ and implemented in the method !od# /ethod s*nta95 attri!utes accessi!ilit# modifiers returnt#pe methodname,parameter listB tatementA _A _A D

Constru tors5 S*nta95 SModifiersH SClass )ameH,parameter list- : S,inititili+er- !ase or thisH Sparameter listH B _% D Modifiers are optional% 2u!lic$ 2rivate$ 2rotected$ 1nternal$ unsafe$ and e/tern are allowed% Constructors are specified as pu!lic !ecause it will call from out side from the class% "here are I t#pes of constructor is availa!le% ,Default constructor will automaticall# invo0e if constructors are not defined%;4 #nstan e Constru tor 24 ,ri"ate Constru tor 24 Stati Constru tor4 1nstance constructors are used to create and initiali+e instances% Constructors are special t#pe of function itFll automaticall# invo0e when the o!3ect is created% 1t is used to initiali+e the varia!les to the class o!3ect%

class 2rogram B int noA string nameA pu!lic 2rogram,int eno$string enameB no O enoA name O enameA D static void Main,stringUV argsB int nA string namA Console%'riteLine,CEnter the Emplo#ee num!er :C-A n O int%2arse,Console%.eadLine,--A Console%'riteLine,CEnter the Emplo#ee name :C-A nam O Console%.eadLine,-A

== paramaters are passed as argument at the time of creating o!3ect 2rogram p O new 2rogram,n$nam-A Console%'riteLine,C)um!er :C@p%no-A Console%'riteLine,C)ame :C@p%name-A Console%.ead,-A D D

2arameter list is optional%

class 2rogram B int noA string nameA == parameter is optional we can also give the value inside the function pu!lic 2rogram,B no O ;0A name O C47CCA D static void Main,stringUV argsB 2rogram p O new 2rogram,-A Console%'riteLine,C)um!er :C@p%no-A Console%'riteLine,C)ame :C@p%name-A Console%.ead,-A

D D

Constructors are not defined then automaticall# default constructor will invo0e and initiali+e all mem!er varia!le to +ero ,for value t#pe- or null ,for reference t#pe-%

E9ample class 2rogram B !ool aA pu!lic 2rogram,B D static void Main,stringUV argsB 2rogram p O new 2rogram,-A Console%'riteLine,p%a-A Console%.ead,-A D D

1f #ou define #our own constructor then default constructor is no longer used%

Constru tor $"erloading 1n C# class ma# having constrcutor$ !ut the# must ta0e parameters% 4 default constructor ,constructor without an# parameters- are alwa#s provided to initiali+e the fields to their default values% "he parameteri+ed constructors inside a class can also !e overloaded% E9ample43

class sum B pu!lic sum,int /$int #B Console%'riteLine,C4ddition of 2 num!er is :C @ ,/ @ #--A D pu!lic sum,int /$ int #$int +B Console%'riteLine,C4ddition of 2 num!er is :C @ ,/ @ #@+--A D static void Main,stringUV argsB sum s; O new sum,;0$20-A sum s2 O new sum,;0$ 20$ I0-A Console%.ead,-A D

initiali+er ,6ptional1nvo0ed !efore the e/ecution of the constructor !od#% "he initiali+er can !e one of the following with an optional argument8list: 5 %ase ,argument8list- sent the arguments to the !ase class constructor 5 this ,argument8listsend to the current class o!3ect constructor

class calc B pu!lic calc,int i$int 3B Console%'riteLine,C4ddition of 2$I arg is :C @ ,i @ 3--A D pu!lic calc,int /$ int #$int +-:this,/$#B Console%'riteLine,C 9uare of ; arg isC @,/M/--A D static void Main,stringUV argsB int a$ !$ cA Console%'riteLine,CEnter I arguments of the ConstructorC-A a O int%2arse,Console%.eadLine,--A ! O int%2arse,Console%.eadLine,--A c O int%2arse,Console%.eadLine,--A calc s; O new calc,a$!$c-A Console%.ead,-A D D

4 private constructor is a special instance constructor%

class program B pu!lic int /$ #A private program,B / O ;0A # O 20A D static void Main,stringUV argsB program p; O new program,-A

Console%'riteLine,p;%/-A Console%'riteLine,p;%#-A Console%.eadLine,-A D

1t is commonl# used in classes that contain static mem!ers onl#% 1n such a case$ other classes ,e/cept nested classes- are not allowed to create instances of this class%

E9ample pu!lic class program B pu!lic static int /O;0A pu!lic int # O 20A private program,B / O 20A D pu!lic class prg B program p; O new program,-A pu!lic void disp,B Console%'riteLine,C1nstance value :C@p;%#-A Console%'riteLine,Cstatic value :C @ program%/-A D D D pu!lic class / B static void Main,stringUV argsB program%prg p O new program%prg,-A p%disp,-A D D )ote that if #ou don(t use an access modifier with the constructor it will still !e private !# default% :owever$ the pri"ate modifier is usuall# used e/plicitl# to ma0e it clear that the class cannot !e instantiated% 2rivate constructors are useful to prevent creation of a class when there are no instance fields or methods E9ample pu!lic class program B pu!lic int /$ #A private program,B / O ;0A # O 20A D D pu!lic class / B static void Main,stringUV argsB == we can(t create an instance if the class having private constructor program p; O new program,-A == show error%% Console%.eadLine,-A Console%.eadLine,-A

D D

4 static constructor is used to initiali+e a class% 1t is called automaticall# to initiali+e the class !efore the first instance is created or an# static mem!ers are referenced% + stati onstru tor does not ta)e a ess modifiers or ha"e parameters %

tatic constructor must !e a private and canFt !e called !# our program% 4 static constructor cannot !e called directl#% "he user has no control on when the static constructor is e/ecuted in the program%

pu!lic class program B pu!lic static int /A ==we should not use modifier and arg in static constructor static program,B / O 20A Console%'riteLine,/-A D static void Main,stringUV argsB ==static constructors invo0ed !efore instance created == we can(t control static constructor invo0e Console%.eadLine,-A D 4 t#pical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file% !estru tors5 1t reclaim o!3ect no longer used and reallocate the memor#% #nta/: aSClass )ameH ,B _% D Destructors are used to destruct instances of classes 4 class can onl# have one destructor% Destructors cannot !e inherited or overloaded% Destructors cannot !e called% "he# are invo0ed automaticall#% 4 destructor does not ta0e modifiers or have parameters% 1t canFt !e a static%

#nheritan e5 a class that inherited is a %ase lass% "he class that does the inheriting is called deri"ed lass4 "herefore the derived class is a speciali+ed version of the !ase class% 1t inheriting all the varia!les$ methods$ a propert# etc%$ from the !ase class and add its own uni9ue elements% S*nta95 :a F G ess spe ifier; lass :deri"ed lass name; 5 :%ase lass name;

'e cannot inherit the private mem!er of the !ase class% 'e can pass the value to the !ase class constructors using the derived class constructor and %ase 0e#word% 5eneral form is :deri"ed lass onstru tor6parameter list75%ase6 arg list7 F G pu!lic class !ase; B pu!lic int #A pu!lic float /A pu!lic !ase;,float a$ int !-:this,aB # O !A Console%'riteLine,#-A D pu!lic !ase;,float iB / O iA Console%'riteLine,/-A D

pu!lic class der : !ase; B pu!lic int sumA pu!lic der,float i$ int 3$ int 0- : !ase,i$ 3B sum O 0A Console%'riteLine,sum-A D D pu!lic class der; : der B pu!lic der;,float m$ int n$ int o-: !ase,m$ n$ oB D D pu!lic class / B static void Main,stringUV argsB der; d O new der;,;0%2f$ 20$ I0-A Console%.eadLine,-A D D

1f more than one constructor in derived class we can use to pass the value to one constructor to another constructor using this 0e#word% 1f the !ase class and derived class propert# or method having the same name then we can hiding the !ase class mem!ers using new 0e#word in front of the derived class mem!er% 4nd we can call the !ase class mem!ers using the S%ase4mem%ername;4 Constructors are called in order of derivation$ form !ase to derived class% &or e/ample$ using #stemA

pu!lic class a B pu!lic a,B Console%'riteLine,CaC-A D D pu!lic class !:a B pu!lic !,B Console%'riteLine,C!C-A D D pu!lic class / B pu!lic static void Main,stringUV argsB ! !;Onew !,-A Console%.eadLine,-A D D &urthermore this order of constructor invo0ing the same order whether the %ase 0e#word is used or not% .eference varia!le for one class t#pe is cannot normall# refer to an o!3ect of another class t#pe% 8or e9ample3 using #stemA

pu!lic class a B int /A pu!lic a,int iB /OiA D D pu!lic class ! B int #A pu!lic !,int 3B #O3A D D pu!lic class / B pu!lic static void Main,stringUV argsB a a;Onew a,;0-A ! !;Onew !,20-A a a2A a2Oa;A == o0$ same t#pe a2O!;A == error not a same t#pe D D 6ne e/ception is there$ ie%$ the reference varia!le of the !ase class can assigned a reference to an o!3ect of an# class derived from !ase class% 8or e9ample

pu!lic class a B pu!lic int /A pu!lic a,int iB /OiA D D pu!lic class !:a B pu!lic int #A pu!lic !,int i$int 3-:!ase,iB #O3A D D pu!lic class / B pu!lic static void Main,stringUV argsB a a;Onew a,;0-A ! !;Onew !,20$I0-A a a2A a2Oa;A == o0$ same t#pe a2%/ O;0A a2O!;A == o0 !ecause ! derived from a ==a2%# O20A == it will show an error !ecause a doesn(t have a # mem!er D D C# defines a spe ial lass alled o%&e t that is an impli it %ase lass for all other lasses and all other t*pes in luding "alue t*pes4 "his means reference varia!le of t#pe o!3ect can refer an o!3ect of an# t#pe% called o%&e t is a generi data t*pe o that we

,ropert*5 1t is a com!ination of field and accessing methods that access it% <sing properties we can resects the range of value that can !e assigned to that field% S*nta95 :modifier; :data t*pe; :propert* name; get F G set F G HmodifierI pu!lic$ private$ protected$ internal and virtual and a!stract modifiers are allowed% Bet K we can access propert# value using get accessor Set K using this accessor to assign the value to the propert#% "#pes of propert# according to the presence and a!sence of get and set accessor% ;% 2% I% readonl# Q get accessor present set accessor a!sent writeonl# 8 set accessor present get accessor a!sent readwrite Q !oth are present

tatic modifier can !e user to create a propert# that !elongs to the same class as opposed to individual o!3ect% 'e can restrict the propert# value with in the range%

pu!lic class d B int iA

pu!lic int # B get B return iA D set B i O valueA D D D pu!lic class prop B pu!lic static void Main,stringUV argsB d d; O new d,-A d;%# O ?0A Console%'riteLine,d;%#-A Console%.eadLine,-A D D

+%stra t5 4!stract classes are concepts% 6!3ect8oriented applications model the real world$ which is replete with concepts% &or developers of a graphics program$ a geometric shape is a concept% :ave #ou even seen a geometric shapeT )o% .ather$ #ou have seen t#pes of geometric shapes$ such as triangles$ ellipses$ rectangles$ and lines% 5eometric shape is a description of a categor#^a 0ind of shape% Conversel#$ a rectangle is tangi!le: 4 television$ a !o/$ and this !oo0 are actual rectangles% +%stra t lass and a%stra t method +%stra t Class5 4 class that contains methods that have no implementation ,4!stract Methods- the class said to !e an a!stract class% 4!stract class canFt !e instantiated%

4!stract modifier indicates that a class is incomplete and indented onl# to !e a !ase class of other class% 4!stract class canFt !e instantiated% 1t is an error to use the new operator on an a!stract class% 4n a!stract class permitted to contain a!stract method$ non8a!stract method and accessor% 4!stract class should have an a!stract method% 4!stract class canFt !e sealed% 4!stract class can have constructors% 4!stract class can have a static methods$ protected mem!ers and partial implementation% 'hen non8a!stract class is derived from an a!stract class$ the non a!stract class must include actual implementation of all inherited methods$ properties and accessors%

'hen implementing the a!stract class$ we must implement each a!stract method in that class$ and each implemented method must receive the same num!er$ and t#pe of arguments and same return value$ as the method specified in the a!stract class% 1nstance method declaration includes an a!stract modifier then it is said !e an a!stract method% ,4!stract method implicitl# virtual method !ut we should not mention with virtual modifier%4n a!stract method provides no actual implementationA the method !od# of an a!stract method simpl# consists of a semicolon% )on8a!stract classes are re9uired to provide their own implementation !# overriding the method% 1f the derived class didnFt provide the implementation of the a!stract method then the derived class must !e an a!stract class ,ie%$ the derived class declared as an a!stract class-A 1f include an# one of the static$ virtual$ or override with a!stract method$ it will show an error% 1n a!stract class we can implements more than one interface%

+%stra t methods 1nstance method declaration includes an a!stract modifier then it is said !e an a!stract method% ,4!stract method implicitl# virtual method !ut we should not mention with virtual modifier% 4n a!stract method provides no actual implementationA the method !od# of an a!stract method simpl# consists of a semicolon% )on8a!stract classes are re9uired to provide their own implementation !# overriding the method% 1f the derived class didnFt provide the implementation of the a!stract method then the derived class must !e an a!stract class ,ie%$ the derived class declared as an a!stract class-A 1f include an# one of the static$ virtual$ or override with a!stract method$ it will show an error%

pu!lic a!stract class a!s; B a!stract pu!lic void a!;,-A pu!lic void nona!,B Console%'riteLine,C)on 4!stract ClassC-A D a!stract pu!lic int no; B setA getA D D pu!lic class der:a!s; B override pu!lic void a!;,B Console%'riteLine,C4!stract ClassC-A D pu!lic int /A override pu!lic int no; B set B /OvalueA D get B return /A D D

D pu!lic class / B static void Main,stringUV argsB der d Onew der,-A d%no; O;0A d%a!;,-A Console%'riteLine,d%no;-A Console%.eadLine,-A D D

#nterfa e5 1t is simpl# a collection of function protot#pes ,onl# declaration of function-% 4 class or structure can implement an interface% S*nta9

:+ F G

ess spe ifier; interfa e name :return t*pe; :fun tion name;6arg13arg2447C

H+

ess spe ifierI is optional% 2u!lic$ private$ protected$ internal are allowed% (* default pu%li 4

Hinterfa eI is a 0e#word to declare the interface% 1nterface mem!ers are !# default pu!lic% 1t will show an error if interface mem!er mention with Modifier even pu!lic% 1nterface ma# have mem!er li0e properties$ methods$ inde/er$ and events%

E9ample interface i; B void displa#,-A int no; B setA getA D D pu!lic class der : i; B pu!lic void displa#,B Console%'riteLine,C1nterface function implementationC-A D pu!lic int /A pu!lic int no; B set B / O valueA D get B return /A D D D

pu!lic class d B pu!lic static void Main,stringUV argsB i; iA der d O new der,-A i O dA i%no; O ;0A i%displa#,-A Console%'riteLine,C"he interface propert# value is C@i%no;-A Console%.eadLine,-A D D 1nterface can onl# have a!stract methods ,implicitl# a!stract- !ut a!stract 0e#word not allowed% 1nterface cannot contain data ,varia!le- declaration% "here is no implementation in an interface% "he class implementing the interface must provide implementation code% 1n order to use interface$ we must declare class in the same wa# that declare a class inheriting from other class% "he class can implements multiple interfaces ,multiple inheritance-

class Cls; B static void Main,stringUV argsB 1&irst f O new &irst,-A 1 econd s O new &irst,-A f%func;,-A f%func2,-A s%funcI,-A s%func?,-A Console%.ead,-A D D interface 1&irst B void func;,-A void func2,-A D interface 1 econd B void funcI,-A void func?,-A D pu!lic class &irst : 1&irst$ 1 econd B pu!lic void func;,B Console%'riteLine,C1&irst func;C-A D pu!lic void func2,B D Console%'riteLine,C1&irst func2C-A

pu!lic void funcI,B Console%'riteLine,C1 econd funcIC-A D

pu!lic void func?,B Console%'riteLine,C1 econd func?C-A D

4n interface can !e derived from another interface,s-%

interface i2 B void inter2,-A D interface i;:i2 B void inter;,-A D pu!lic class der : i; B pu!lic void inter;,B Console%'riteLine,C1nterface i; function%%%C-A D pu!lic void inter2,B Console%'riteLine,C1nteface i2 function%%%C-A D D pu!lic class d B pu!lic static void Main,stringUV argsB i; iA der d O new der,-A i O dA i%inter;,-A i%inter2,-A Console%.eadLine,-A D D 1nterface canFt have a constructor% 'e cannot specif# new 0e#word in front of the interface% 1nterface cannot !e instantiated% 'e can create a reference varia!le$ and call a method on an o!3ect through an interface reference% &or e/ample$

interface i; B void displa#,-A D pu!lic class der:i; B pu!lic void displa#,B Console%'riteLine,ChaiC-A D D pu!lic class d

pu!lic static void Main,stringUV argsB i; iA der dOnew der,-A iOdA i%displa#,-A Console%.eadLine,-A D

1nterfaces are implicitl# a!stract$ and interface mem!ers also implicitl# a!stract% 4n a!stract method implicitl# virtual% o interface mem!ers are implicitl# virtual%

"wo interfaces are implemented and !oth interfaces having the same method then e/plicit implementation is used to eliminate the am!iguit#% ,ie%$ in implemented class we should mention the SinterfacenameH4SmethodnameH-% &or e/ample%%

using

#stemA

interface i; B void displa#,-A D interface i2 B void displa#,-A D pu!lic class der:i;$i2 B void i;%displa#,B Console%'riteLine,Ci;C-A D void i2%displa#,B Console%'riteLine,Ci2C-A D pu!lic void call;,B i; aA aOthisA a%displa#,-A D pu!lic void call2,B i2 aA aOthisA a%displa#,-A D pu!lic class / B pu!lic static void Main,stringUV argsB der dOnew der,-A d%call;,-A d%call2,-A Console%.eadLine,-A D D +%stra t lass "s4 interfa es

+%stra t lass Ma# or ma# not have a!stract methods% Methods can have access modifiers% Can have fields% Can !e instantiated via su!8class% Can e/tend a interfaces% ingle class$ implement one or more

#nterfa e Can onl# have a!stract methods ,1mplicitl# a!stract- !ut a!stract 0e#word is not allowed% )o access modifier is allowed$ implicitl# pu!lic% )ot intended to define fields% Can !e instantiated via implementing class% Cannot e/tend a class$ Can e/tend single or multiple interfaces% 1nterfaces do not% 'e can use the same interface in two pro3ects that are not related in terms of inheritance% &or e/ample an interface 1'heel can !e implemented in a Car pro3ect and also a 7ic#cle pro3ect% Can(t have constructor% 1nterfaces provide a form of multiple inheritance ,Cinterface inheritanceC-$ !ecause #ou can implement multiple interfaces% 1nterfaces are limited to pu!lic methods and constants with no implementation allowed%

4!stract classes form part of the inheritance scheme

Can have constructor% 4 class$ !# comparison$ can onl# e/tend ,Cimplementation inheritanceC- one other class 4n a!stract class can have static methods$ protected parts$ and a partial implementation%

6verView :8

4n 1nterface cannot implement methods% 4n a!stract class can implement methods% 4n 1nterface can onl# inherit from another 1nterface% 4n a!stract class can inherit from a class and one or more interfaces% 4n 1nterface cannot contain fields% 4n a!stract class can contain fields% 4n 1nterface can contain propert# definitions% 4n a!stract class can implement a propert#% 4n 1nterface cannot contain constructors or destructors% 4n a!stract class can contain constructors or destructors% 4n 1nterface can !e inherited from !# structures% 4n a!stract class cannot !e inherited from !# structures% 4n 1nterface can support multiple inheritance% 4n a!stract class cannot support multiple inheritance

!elegate5 4 delegate is an a!straction of one or more function pointers% Delegates are derived from System.Multicast'elegate$ which is a reference t#pe% System.Multicast'elegate is derived from System.'elegate% "he delegate classes offer a pu!lic interface for initiali+ing$ adding$ removing$ and invo0ing delegates

!elegates 5 1t is an o!3ect that can refer to a method% 'hen we creating delegates$ creating an o!3ect that can hold a reference to a method% "he method can call through this reference%

Creating and in"o)ing delegate in"ol"e four steps5 ;% 2% I% ?% Delegate declaration delegate method definition delegate instantiate delegate invocation

+d"antages 5 Events are achieved through delegates% "he method that will !e invo0ed !# the delegates is not determined at compile time$ !ut rather at runtime$ ie%$ the same delegate can used to call different methods during the runtime of program !# simpl# changing the method to which the delegate refers% S*nta9 5 delegate Sreturn8t#peH SnameH,parameter list-A HdelegateP is the 0e#word to declare the delegate Hreturn?t*peP is the t#pe of value returned !# the methods that the delegate will !e calling% Hname is name of the delegate% Hparameter listI parameter list re9uired !# the method called through the delegate are specified in parameter list% Delegate can invo0e either static method associated with the class or instance method associated with an o!3ect% 4ll that maters is that the return t*pe and the signature of the method agree with the delegate4 the

using

#stemA

delegate int samp,int /$int #-A== delegate declaration pu!lic class del B pu!lic static int add;,int i$int 3- ==static method B return i@3A D pu!lic int add2,int a$ int !- == instance method B return a@!A D static void Main,stringUV argsB int a$!A del dOnew del,-A == creating an instance and pass the function% samp sOnew samp,add;-A Console%'riteLine,s,a$!--A Console%'riteLine,CEnter the two num!ersC-A

D D

aOint%2arse,Console%.eadLine,--A !Oint%2arse,Console%.eadLine,--A sOnew samp,d%add2-A Console%'riteLine,s,?0$50--A sOnew samp,d%addI-A

/ulti Casting5 1t is the a!ilit# to create an invocation list or chain of methods that will !e automaticall# called when the delegate is invo0ed% 1f we want to create the 1nvocation list simpl# instantiate the delegate$ and then use the @O to add the method to the chain$ or Q O to remove the method from the chain% "he onl# restriction is that the delegate !eing multi ast must ha"e a "oid return t*pe4 #stemA

using

delegate void disp,-A pu!lic class del B pu!lic static void d;,B Console%'riteLine,C"his is D;C-A D pu!lic static void d2,B Console%'riteLine,C"his is D2C-A D pu!lic static void dI,B Console%'riteLine,C"his is DIC-A D static void Main,stringUV argsB disp dA disp de;Onew disp,d;-A disp de2Onew disp,d2-A disp deIOnew disp,dI-A dOde;A d@Ode2A Console%'riteLine,C4fter d,-A d@OdeIA Console%'riteLine,C4fter d,-A d8Ode2A Console%'riteLine,C4fter d,-A d8OdeIA Console%'riteLine,C4fter d,-A Console%.eadLine,-A D D

4dding the d; [ d2 functions :C-A 4dding the DI function :C-A remove the d2 function :C-A remove the dI function :C-A

E"ents5 4 call !ac0 function is a function in which one piece of code implements another function% 1t is an automatic notification that some action has occurred% Events ma# invo0e static or instance methods% S*nta95 event event8delegate o!3ectA He"entI is a 0e#word to declare the event% He"ent?delegateI is a delegate used to support the event Ho%&e tI is the name of the specified o!3ect is created% using #stemA == delegate declaration pu!lic delegate void edelegate,-A

pu!lic class evnt B pu!lic event edelegate event;A pu!lic void raise,B == raise event ma# call !efore the event handler has !een register% if ,event; YO nullevent;,-A

D D

pu!lic class / B pu!lic static void fun,B Console%'riteLine,C"his is called when the event fires%C-A D static pu!lic void Main ,B evnt i O new evnt,-A i%event; @O new edelegate,fun-A i%raise,-A Console%.eadLine,-A D D

/ulti?Cast E"ents5 "his ena!les multiple o!3ects to respond to an event notification% using #stemA

pu!lic delegate void edelegate,-A pu!lic class evnt B pu!lic event edelegate event;A pu!lic void raise,B if,event; YOnullevent;,-A D D pu!lic class / B pu!lic void /fun,B Console%'riteLine,C/fun is calledC-A D

D pu!lic class # B pu!lic void #fun,B Console%'riteLine,C#fun is calledC-A D D pu!lic class + B pu!lic static void +fun,B Console%'riteLine,Cstatic fun is calledC-A D pu!lic static void Main,stringUV argsB evnt eOnew evnt,-A / /;Onew /,-A # #;Onew #,-A e%event; @Onew edelegate,/;%/fun-A e%event; @Onew edelegate,#;%#fun-A e%event; @Onew edelegate,+fun-A e%raise,-A e%event; 8Onew edelegate,+fun-A Console%'riteLine,C4fter deleting static fun %%%C-A e%raise,-A Console%'riteLine,C4fter deleting /fun %%%C-A e%event; 8Onew edelegate,/;%/fun-A e%raise,-A Console%.eadLine,-A

D D

stati method also used as a e"ent handler4 using #stemA

pu!lic delegate void edelegate,-A pu!lic class evnt B pu!lic event edelegate event;A pu!lic void raise,B if,event; YOnullevent;,-A D D pu!lic class / B pu!lic static void staticfun,B Console%'riteLine,Cstatic is calledC-A D D

pu!lic class + B pu!lic static void Main,stringUV argsB

evnt eOnew evnt,-A e%event; @Onew edelegate,/%staticfun-A e%raise,-A Console%.eadLine,-A D E"ent + D essors5 ;% 2% Event that automaticall# manage the event handler invocation list$ including add or su!tract of event handlers and form the list% 'e ma# provide the event handler list operation our self8using speciali+ed event storage mechanism% <sing Event 4ccessors we control over how the event handler list is implemented%

'here are two form of e"ent statement4

S*nta95 event event8delegate event8name B add B

_% D remove B _% D

H add H add accessor is called when an event handler is added to the event chain !# using @O% % H remo"e H remove accessor is called when an event handler is removed the event from the chain !# using 8 O% 'hen HaddI or Hremo"eI is called it receives the handler to add or remove as a parameter% "his parameter is called "alue% 7# implementing the HaddI and Hremo"eI we can define custom event storage% E/ample arra*3 sta )3 =ueue to store handlers%

using

#stemA

pu!lic delegate void edelegate,-A == pu!lic 0e#word must pu!lic class evnt B edelegateUV evnsOnew edelegateUIVA pu!lic event edelegate e; B add B for,int iO0AiSIAi@@B if,evnsUiVOOnullB evnsUiVOvalueA !rea0A if,iOO2Console%'riteLine,CEvent list full %%% C-A D

D remove B

for,int iO0AiSIAi@@B if,evnsUiVOOvalueB evnsUiVOnullA !rea0A if,iOO2Console%'riteLine,CEvent handler not found%%% C-A D D D D

pu!lic void raise,B for,int iO0AiSIAi@@B if,evnsUiVYOnullevnsUiV,-A D

pu!lic class w B pu!lic void wfun,B Console%'riteLine,Cwfun calledC-A D D pu!lic class / B pu!lic void /fun,B Console%'riteLine,C/fun calledC-A D D pu!lic class # B pu!lic void #fun,B Console%'riteLine,C#fun calledC-A D D pu!lic class + B pu!lic void +fun,B Console%'riteLine,C+fun calledC-A D D pu!lic class a B pu!lic static void Main,stringUV argsB evnt eOnew evnt,-A w w;Onew w,-A / /;Onew /,-A # #;Onew #,-A + +;Onew +,-A

e%e; @Onew edelegate,w;%wfun-A e%e; @Onew edelegate,/;%/fun-A e%e; @Onew edelegate,#;%#fun-A e%raise,-A Console%.eadLine,-A D D )amespace : +rra*list #stem%CollectionsA

4rra#list is a simple resi+a!le$ inde/ !ased on the collection of o!3ects 4n arra# list is a d#namic arra#% 4lthough indigenous arra#s are static$ elements can !e added or removed from an ArrayList at run time% Elements of the ArrayList are not automaticall# sorted% elements are added% 4dd function is used to add the value at the end of the 4rra#List ,return t#pe is intarr%4dd,;2-A arr%4dd,Ca!cC-A 4dd.ange is used to add the range of value from collections ,return t#pe is voidintUV / O new intUIV B K$ 5$ ; DA arr%4dd.ange,/-A 7inar# earch function is used to find the specific element inde/ position ,return t#pe is intConsole%'riteLine,C"he position is :C @ arr%7inar# earch,I?--A Capasit# propert# is used to get the capacit# of the arra#list ,return t#pe is intConsole%'riteLine,arr%Capacit#-A Clear method is used to clear the elements in the arra#list ,return t#pe is voidarr%Clear,-A imilar to single8dimensional arra#s$ the elements of an ArrayList are accessi!le using the inde/ing operator and indices% 4rra#list automaticall# grow when the

Clone method is used to cop# all the element to new colection ,return t#pe is o!3ect4rra#List arr; O new 4rra#List,-A arr; O ,4rra#List-arr%Clone,-A Contains method is used to find the specific element is availa!le in the collection or not ,return t#pe is !oolConsole%'riteLine,Cthe element is availa!le TC @ arr%Contains,K--A

Cop#"o method is used to cop# the elements to another collection return t#pe is void intUV cp O new intU;0VA arr%Cop#"o,cp-A Count propert# is used to count the num!er of elements there at present ,return t#pe is int-

Console%'riteLine,C"he elements in the collection is :C @ arr%Count-A

E9ual is used to find the current collection t#pe with another t#pe ,return t#pe is !oolConsole%'riteLine,C"he elements are e9ual T :C @ arr%E9uals,arr--A 5et.ange method is used to get the range of value to the another collection ,return t#pe is collection t#pearr; O ,4rra#List-arr%5et.ange,;$ 2-A 5et"#pe method is used to find the t#pe of the collection "#pe t O arr%5et"#pe,-A Console%'riteLine,C"he t#pe of the arr coollection is :C @ t-A 1nde/6f method is used to find the inde/ position of element ,return t#pe is intConsole%'riteLine,C"he inde/ value of K is :C @ arr%1nde/6f,K--A 1nsert method is used to insert item in specific position arr%1nsert,?$ C/#+C-A 1nsert.ange is used to insert the range of value to the specific position% arr%1nsert.ange,;$ cp-A Last1nde/ is used to search the specific element using reverse order Console%'riteLine,C"he position of K using lastinde/ :C @ arr%Last1nde/6f,K--A .emove method is used to remove the specific element from the collection arr%.emove,K-A .emove4t method is used to remove the specific element using the inde/ position arr%.emove4t,I-A .emove.ange method is used to remove the range of value !# using inde/ position and num!er of element arr%.emove.ange,?$ I-A .everse Method is used to reverse the order of the collection elements arr%.everse,-A ort is used to sort the elements% arr;% ort,-A "rim"o i+e is used to trim the arra#list with element count arr%"rim"o i+e,-A

Jashta%le Colle tion

"he :ashta!le collection is a collection of 0e#=value pairs% Entries in this collection are instances of the Dictionar#Entr# t#pe% Dictionar#Entr# t#pes have a Ee# and Value propert# to get and set 0e#s and values% 1n addition to the standard collection interfaces$ the :ashta!le collection implements the 1Dictionar#$ 1 eriali+a!le$ and 1Deseriali+ationCall!ac0 interfaces% "he entries are stored and retrieved in order !ased on a hash code of the 0e#% class 2rogram B static void Main,stringUV argsB :ashta!le h O new :ashta!le,-A == 4dd the element to hash ta!le hUC;2ICV O C;2IZ#ahoo%comCA hUC/#+CV O C/#+Z#ahoo%comCA hUCaaaCV O CaaaZ#ahoo%comCA == 4dd method is used to add the element to the the hashta!le h%4dd,Ca!cC$ Ca!cZ#ahoo%comC-A == Clear method is used to clear the elements h%Clear,-A foreach ,Dictionar#Entr# i in hB Console%'riteLine,CB0D mail id is :B;DC$i%Ee#$i%Value-A D Console%.ead,-A

D D

Lueue Colle tion bueue collections a!stract &1&6 data structures% "he initial capacit# is I2 elements% bueue collections are ideal for messaging components% class 2rogram B static void Main,stringUV argsB bueue 9 O new bueue,-A == En9ue method is used to add the elements to the bueue 9%En9ueue,C;2IC-A 9%En9ueue,C;2IC-A 9%En9ueue,C;2IC-A 9%En9ueue,C;2IC-A == De9ueue .emove the element from the 9ueue and it return the element 9%De9ueue,-A == Clear the elements from 9ueue == 9%Clear,-A == 2ea0 is used to return the first element of the bueue

Console%'riteLine,C"he first element of the bueue :C@9%2ee0,--A ==while ,9%Count H 0==B == Console%'riteLine,9%De9ueue,--A ==D 1Enumerator e O 9%5etEnumerator,-A while ,e%Move)e/t,-B Console%'riteLine,e%Current-A D D D Console%.ead,-A

Sta ) Colle tion tac0 collections a!stract L1&6 data structures in which the initial capacit# is I2 elements% class 2rogram B static void Main,stringUV argsB tac0 s O new tac0,-A == 2ush method is used to add the elements to the stac0 s%2ush,;2-A s%2ush,;0-A s%2ush,;2-A s%2ush,;0-A == 2op method is used to remove and return the element from stac0 Console%'riteLine,s%2op,--A 1Enumerator e O s%5etEnumerator,-A while ,e%Move)e/t,-B Console%'riteLine,e%Current-A D Console%.ead,-A D D

Beneri data'*pe5 class 2rogram B static void Main,stringUV argsB tac0SintH sta0 O new tac0SintH,-A sta0%2ush,;2-A sta0%2ush,int%2arse,C;5C--A bueueSstringH b O new bueueSstringH,-A b%En9ueue,Can!C-A

Console%.ead,-A D D #nde9er 5 1nde/ers are the location indicators and are used to access class o!3ects$ 3ust li0e accessing elements in an arra#% "he# are used in cases where a class is a container for other o!3ects% W1nde/ers are sometime 0nown as smart arra#sP% Saccessor specifierH Sreturn t#peH thisUint ind/V B get B D et B D D 1nde/ers are ta0es an inde/ argument and loo0 li0e an arra#% 1nde/er is declaried using the name this% 1mplementation rules for get and set accessors are the same as for properties% 1nde/er and propert# are ver# similar concept !ut differ in following wa#s% 4 propert# can !e a static whereas an inde/er is alwa#s an instance mem!er 4 get accessor of a propert# corresponds to a method with no parameters$ whereas a get accessor of an inde/er corresponds to a method with the same formal parameter list as the inde/er% 4 set accessor of a propert# corresponds to a method with a single parameter named value$ whereas a set accessor of an inde/er$ plus parameter named value 1t is an error for an inde/er to declare a local varia!le with a same name as an inde/ parameter% pu!lic class 2rogram B o!3ectUV arr6! O new o!3ectUIVA pu!lic o!3ect thisUint ind/V B get B return arr6!Uind/VA D set B arr6!Uind/V O valueA D D static void Main,stringUV argsB 2rogram o! O new 2rogram,-A o!%arr6!U0V O ;0A Console%'riteLine,o!%arr6!U0V-A

D D

Console%.ead,-A

E9 eption Jandling #n C# Definition: CE*CE2"16) 1 4 .<)"1ME E..6. ':1C: 4.1 E 7EC4< E 6& 47)6.M4L C6)D1"16) 1)4 C6DE Eb<E)CE% C 1n C# E/ception is a class in the s#stem namespace% 4n o!3ect of an e/ception is that descri!e the e/ceptional conditions occur in a code "hat means$ we are catching an e/ception$ creating an o!3ect of it$ and then throwing it% C# supports e/ceptions in a ver# much the same wa# as Xava and C@@% 7efore going into detail$ 1 must sa# the usefulness of 0nowing and performing e/ception handling : "he# cannot !e ignored$ as if calling code does not handle the error$ it causes program termination% "he# do not need to !e to !e handled at the point where error too0 place% "his ma0es them ver# suita!le for li!rar# or s#stem code$ which can signal an error and leave us to handle it "he# can !e used when passing !ac0 a return value cannot !e used% E/ceptions are handled !# using tr#catch statements% Code which ma# give rise to e/ceptions is enclosed in a tr# !loc0 $ which is followed !# one or more catch !loc0s% E9 eption Jierar h* "here are two t#pes of e/ceptions: e/ceptions generated !# an e/ecuting program$ and e/ceptions generated !# the common language runtime% 1n addition$ there is a hierarch# of e/ceptions that can !e thrown !# either an application or the runtime% E/ception is the !ase class for e/ceptions% everal e/ception classes inherit directl# from E9 eption$ including 4pplicationE/ception and #stemE/ception% "hese two classes form the !asis for almost all runtime e/ceptions% Most e/ceptions that derive directl# from E9 eption add no functionalit# to the E9 eption class% &or e/ample$ the 1nvalidCastE/ception Class hierarch# is as follows: 6!3ect E9 eption S*stemE9 eption #n"alidCastE9 eption "he runtime throws the appropriate derived class of S*stemE9 eption when errors occur% "hese errors result from failed runtime chec0s ,such as arra# out8of8!ound errors-$ and can occur during the e/ecution of an# method% 1f #ou are designing an application that creates new e/ceptions$ #ou should derive those e/ceptions from the E/ception class% 1t is not recommended that #ou catch a S*stemE9 eption$ nor is it good programming practice to throw a S*stemE9 eption in #our application% "he most severe e/ceptions ^ those thrown !# the runtime or in nonrecovera!le conditions ^ include E/ecutionEngineE/ception$ tac06verflowE/ception$ and 6ut6fMemor#E/ception% 1nteroperation e/ceptions derive from S*stemE9 eption and are further e/tended !# E/ternalE/ception% &or e/ample$ C6ME/ception is the e/ception thrown during C6M interop operations and derives from E9ternalE9 eption% 'inI2E/ception and E:E/ception also derive from E9ternalE9 eption% "here are a num!er of e/ception classes provided !# C#$ all of which inherit from the &ollowing are some common e/ception classes% E/ception Class #stemE/ception 4ccessE/ception 4rgumentE/ception 4rgument)ullE/ception Cause 4 failed run8time chec0Aused as a !ase class for other% &ailure to access a t#pe mem!er$ such as a method or field% 4n argument to a method was invalid% 4 null argument was passed to a method that doesn(t accept it% #stem%E/ception class%

4rgument6ut6f.angeE/ception 4rgument value is out of range% 4rithmeticE/ception 4rra#"#peMismatchE/ception 7ad1mage&ormatE/ception CoreE/ception Divide7#ceroE/ception 4rithmetic over 8 or underflow has occurred% 4ttempt to store the wrong t#pe of o!3ect in an arra#% 1mage is in the wrong format% 7ase class for e/ceptions thrown !# the runtime% 4n attempt was made to divide !# +ero%

&ormatE/ception 1nde/6ut6f.angeE/ception 1nvalidCastE/pression 1nvalid6perationE/ception MissingMem!erE/ception )ot&inite)um!erE/ception )ot upportedE/ception )ull.eferenceE/ception 6ut6fMemor#E/ception tac06verflowE/ception

"he format of an argument is wrong% 4n arra# inde/ is out of !ounds% 4n attempt was made to cast to an invalid class% 4 method was called at an invalid time% 4n invalid version of a DLL was accessed% 4 num!er is not valid% 1ndicates sthat a method is not implemented !# a class% 4ttempt to use an unassigned reference% )ot enough memor# to continue e/ecution% 4 stac0 has overflown%

"he finall# !loc0 is used to do all the clean up code% 1t does not support the error message$ !ut all the code contained in the finall# !loc0 is e/ecuted after the e/ception is raised% 'e can use this !loc0 along with tr#8catch and onl# with catch too% "he finall# !loc0 is e/ecuted even if the error is raised% Control is alwa#s passed to the finall# !loc0 regardless of how the tr# !loc0s e/its Jandling C$/ #nterop E9 eptions Managed and unmanaged code can wor0 together to handle e/ceptions% 1f a method throws an e/ception in managed code$ the common language runtime can pass an :.E <L" to a C6M o!3ect% 1f a method fails in unmanaged code !# returning a failure :.E <L"$ the runtime throws an e/ception that can !e caught !# managed code% "he runtime automaticall# maps the :.E <L" from C6M interop to more specific e/ceptions% &or e/ample$ E\4CCE DE)1ED !ecomes <nauthori+ed4ccessE/ception$ E\6<"6&MEM6.N !ecomes 6ut6fMemor#E/ception$ and so on% 1f the :.E <L" is a custom result or if it is un0nown to the runtime$ the runtime passes a generic C6ME/ception to the client% "he ErrorCode propert# of the C$/E9 eption contains the :.E <L" value% &or a complete discussion of C6M interop$ see 4dvanced C6M 1nteropera!ilit#% Wor)ing with #Error#nfo 'hen an error is passed from C6M to managed code$ the runtime populates the e/ception o!3ect with error information% C6M o!3ects that support 1Error1nfo and return :.E <L" provide this information to managed code e/ceptions% &or e/ample$ the runtime maps the Description from the C6M error to the e/ception(s Message propert#% 1f the :.E <L" provides no additional error information$ the runtime fills man# of the e/ception(s properties with default values% 1f a method fails in unmanaged code$ an e/ception can !e passed to a managed code segment% "he topic :.E <L" and E/ceptions contains a ta!le showing how :.E <L" map to runtime e/ception o!3ects% E/ample using #stemA using #stem%Collections%5enericA using #stem%"e/tA lass 2rogram B stati "oid Main,stringUV argsB Console%'riteLine,C2lease enter an integer and press EnterC-A int num!erEnteredA while,Yint%"r#2arse,Console%.eadLine,-$ out num!erEntered--B Console%'riteLine,C2lease tr# againC-A D Console%'riteLine,CNou entered C @ num!erEntered%"o tring,--A D D E/ample using #stemA pu%li lass CatchError B pu%li stati "oid Main,B int var; O ;000$ var2 O 0$ varIA tr* B

D D

varI O var; = var2A D at h ,4rithmeticE/ception eB Console%'riteLine,CE/ception: B0DC$ e%"o tring,--A varI O 8;A D at h ,E/ception eB Console%'riteLine,CE/ception: B0DC$ e%"o tring,--A varI O 82A D Console%'riteLine,C"he result is: B0DC$ varI-A

'ith &inall# 7loc0:8 <sing #stemA pu!lic class "hrowE/ception;4pp B pu!lic static void "hrowE/ception,B throw new E/ception,-A D pu!lic static void Main,B tr# B Console%'riteLine,Ctr#%%%C-A D catch,E/ception eB Console%'riteLine,Ccatch%%%C-A D finall# B Console%'riteLine,Cfinall#C-A D D

E/ample with &ile 1=6 6peration:8 == method with return t#pe of tream.eader% pu!lic tream.eader open&ile, string file\name B if , file\name OO null throw new 4rgument)ullE/ception,-A == reach here onl# if no 4rgument)ullE/ception thrown if , Y &ile%E/ists, file\name -B string msg O C1nvalid file name: C @ file\nameA throw new 4rgumentE/ception, msg -A D == reach here if file\name not null and file e/ists if , Y file\name%Ends'ith, C%t/tC -B string msg O C orr#% CA string e/t O 2ath%5etE/tension, file\name -A if , e/t YO tring%Empt# msg @O C'e currenl# do not support C @ e/t @ C files%CA msg O CGnCurrenl# we onl# support %t/t files%CA throw new E/ception, msg -A D == 6E: here onl# if no e/ceptions thrown return &ile%6pen"e/t, file\name -A

&ile 1=6 6peration 8ile and Stream #M$ "he #stem%16 namespace contains t#pes that allow s#nchronous and as#nchronous reading and writing on data streams and files% "he following distinctions help clarif# the differences !etween a file and a stream% 4 file is an ordered and named collection of a particular se9uence of !#tes having persistent storage% "herefore$ with files$ one thin0s in terms of director# paths$ dis0 storage$ and file and director# names% 1n contrast$ streams provide a wa# to write and read !#tes to and from a !ac0ing store that can !e one of several storage mediums% Xust as there are several !ac0ing stores other than dis0s$ there are several 0inds of streams other than file streams% &or e/ample$ there are networ0$ memor#$ and tape streams% Classes @sed for 8ile #M$ Director# provides static methods for creating$ moving$ and enumerating through directories and su!directories% "he !ire tor*#nfo class provides instance methods% Director#1nfo provides instance methods for creating$ moving$ and enumerating through directories and su!directories% "he !ire tor* class provides static methods% Drive1nfo provides instance methods for accessing information a!out a drive% &ile provides static methods for the creation$ cop#ing$ deletion$ moving$ and opening of files$ and aids in the creation of a &ile tream% "he 8ile#nfo class provides instance methods% &ile1nfo provides instance methods for the creation$ cop#ing$ deletion$ moving$ and opening of files$ and aids in the creation of a &ile tream% "he 8ile class provides static methods% &ile tream supports random access to files through its ee0 method% 8ileStream opens files s#nchronousl# !# default$ !ut supports as#nchronous operation as well% 8ile contains static methods$ and 8ile#nfo contains instance methods% &ile #stem1nfo is the a!stract !ase class for 8ile#nfo and !ire tor*#nfo% 2ath provides methods and properties for processing director# strings in a cross8platform manner% Deflate tream provides methods and properties for compressing and decompressing streams using the Deflate algorithm% 5cip tream provides methods and properties for compressing and decompressing streams% 7# default$ this class uses the same algorithm as the !eflateStream class$ !ut can !e e/tended to use other compression formats% erial2ort provides methods and properties for controlling a serial port file resource% 8ile$ 8ile#nfo$ !ri"e#nfo$ ,ath$ !ire tor*3 and !ire tor*#nfo are sealed ,in Microsoft Visual 7asic$ Not#nherita%le - classes% Nou can create new instances of these classes$ !ut the# cannot have derived classes% Classes @sed for Reading from and Writing to Streams 7inar#.eader and 7inar#'riter read and write encoded strings and primitive data t#pes from and to Streams% tream.eader reads characters from Streams$ using Encoding to convert characters to and from !#tes% StreamReader has a constructor that attempts to ascertain what the correct En oding for a given Stream is$ !ased on the presence of an En oding8specific pream!le$ such as a !#te order mar0% tream'riter writes characters to Streams$ using En oding to convert characters to !#tes% tring.eader reads characters from Strings% StringReader allows #ou to treat Strings with the same 421$ so #our output can !e either a Stream in an# encoding or a String% tring'riter writes characters to Strings% StringWriter allows #ou to treat Strings with the same 421$ so #our output can !e either a Stream in an# encoding or a String%

"e/t.eader is the a!stract !ase class for StreamReader and StringReader% 'hile the implementations of the a!stract Stream class are designed for !#te input and output$ the implementations of 'e9tReader are designed for <nicode character output% "e/t'riter is the a!stract !ase class for StreamWriter and StringWriter% 'hile the implementations of the a!stract Stream class are designed for !#te input and output$ the implementations of 'e9tWriter are designed for <nicode character input% #M$ and Se urit* 'hen using the classes in the S*stem4#$ namespace$ operating s#stem securit# re9uirements such as access control lists ,4CLs- must !e satisfied for access to !e allowed% "his re9uirement is in addition to an# &ile162ermission re9uirements% using #stemA using #stem%16A pu!lic class Comp7uf B private const string &1LE\)4ME O CM#&ile%t/tCA pu!lic static void Main, tringUV argsB if ,Y&ile%E/ists,&1LE\)4ME-B Console%'riteLine,CB0D does not e/istYC$ &1LE\)4ME-A returnA D &ile tream fs1n O new &ile tream,&1LE\)4ME$ &ileMode%6pen$ &ile4ccess%.ead$ &ile hare%.ead-A == Create an instance of tream.eader that can read == characters from the &ile tream% tream.eader sr O new tream.eader,fs1n-A == 'hile not at the end of the file$ read lines from the file% while ,sr%2ee0,-H8;B tring input O sr%.eadLine,-A Console%'riteLine ,input-A D sr%Close,-A D D == "his Event is for save the file into the dis0 private void !utton;\Clic0,o!3ect sender$ Event4rgs eB if ,Dialog.esult%6E OO Message7o/% how,Cu want to sav to another fileC$C'arningC$Message7o/7uttons%6ECancel-B te/t7o/;%Visi!le O trueA te/t7o/;%&ocus,-A D else te/t7o/;%Visi!le O falseA D pu!lic void savetofile,B &ile tream f\stream O new &ile tream,te/t7o/;%"e/t%"rim,-$ &ileMode%6pen6rCreate$ &ile4ccess%.ead'rite-A tream'riter sw O new tream'riter,f\stream-A sw%7ase tream% ee0,0$ ee06rigin%End-A sw%'riteLine,rich"e/t7o/;%"e/t-A Message7o/% how,C aved%%%%C-A sw%Close,-A rich"e/t7o/;%Clear,-A

D == 'rite the code in the te/t!o/ 0e#press events private void te/t7o/;\Ee#2ress,o!3ect sender$ Ee#2ressEvent4rgs eB if ,e%Ee#Char OO ;IB

D D

savetofile,-A

"o retrieve the saved file from the dis0 private void !utton2\Clic0,o!3ect sender$ Event4rgs eB &ile tream f\stream O new &ile tream,te/t7o/;%"e/t%"rim,-$ &ileMode%6pen6rCreate$ &ile4ccess%.ead'rite-A tream.eader sr O new tream.eader,f\stream-A sr%7ase tream% ee0,0$ ee06rigin%7egin-A rich"e/t7o/;%"e/t O sr%.ead"oEnd,-A sr%Close,-A D <sing tream .eader and tream'riter Class insert and retrieve the file

private void !utton?\Clic0,o!3ect sender$ Event4rgs eB tream.eader reader O new tream.eader,Cc:GGinfile%t/tC-A == "e/t in from file tream'riter writer O new tream'riter,Cc:GGoutfile%t/tC-A == "e/t out to file string lineA while ,,line O reader%.eadLine,-- YO nullB writer%'riteLine,line-A D reader%Close,-A writer%Close,-A Message7o/% how,C< file can !e written to outfile%t/tC-A D <sing Director# Class list the director# information and file information == and displa#ed in the list!o/ tool% private void !utton5\Clic0,o!3ect sender$ Event4rgs eB Director#1nfo di O new Director#1nfo,Cc:GGwindowsC-A Message7o/% how,di%&ull)ame-A Message7o/% how,di%Last4ccess"ime%"o tring ,--A Director#1nfo di; O new Director#1nfo,ZCc:GC-A &ile1nfoUV fi O di;%5et&iles,-A foreach ,&ile1nfo file in filist7o/;%1tems%4dd,file%)ame @C C@ file%Length-A D Encoder and Decoder private void !utton>\Clic0,o!3ect sender$ Event4rgs eB la!el;%"e/t O CCA !#teUV !#tes; O B 0/II$ 0/2I$ 0/e2 DA !#teUV !#tes2 O B 0/KL$ 0/eI DA charUV chars O new charUIVA Decoder d O Encoding%<"&L%5etDecoder,-A == Decoder ;%; Version int charLen O d%5etChars,!#tes;$ 0$ !#tes;%Length$ chars$ 0-A == "he value of charLen should !e 2 now% charLen @O d%5etChars,!#tes2$ 0$ !#tes2%Length$ chars$ charLen-A foreach ,char c in charsla!el;%"e/t @O C<@C @ ,,ushort-c-%"o tring,- @ C CA

Decoder ;%2 Version private void !uttonJ\Clic0,o!3ect sender$ Event4rgs eB !#teUV !#tes; O B 0/20$ 0/2I$ 0/e2 DA !#teUV !#tes2 O B 0/KL$ 0/aI DA charUV chars O new charUIVA

Decoder d O Encoding%<"&L%5etDecoder,-A int charLen O d%5etChars,!#tes;$ 0$ !#tes;%Length$ chars$ 0-A == "he value of charLen should !e 2 now% charLen @O d%5etChars,!#tes2$ 0$ !#tes2%Length$ chars$ charLen-A foreach ,char c in charsla!el;%"e/t @O C<@C @ ,ushort-cA

== 4nother E/ample class 2rogram B static void Main,stringUV argsB == "hese !#tes in <"&8L correspond to I different <nicode == characters: space ,<@0020-$ # ,<@002I-$ and the !ioha+ard == s#m!ol ,<@2>2I-% )ote the !ioha+ard s#m!ol re9uires I !#tes == in <"&8L ,he/adecimal e2$ KL$ eI-% Decoders store state across == multiple calls to 5etChars$ handling the case when one char == is in multiple !#te arra#s% ==!#teUV !#tes; O B 0/20$ 0/2I$ 0/e2 DA ==!#teUV !#tes2 O B 0/KL$ 0/eI DA ==charUV chars O new charUIVA ==Decoder d O Encoding%<"&L%5etDecoder,-A ==int charLen O d%5etChars,!#tes;$ 0$ !#tes;%Length$ chars$ 0-A ==== "he value of charLen should !e 2 now% ==charLen @O d%5etChars,!#tes2$ 0$ !#tes2%Length$ chars$ charLen-A ==foreach ,char c in chars== Console%'rite,C<@C @ ,,ushort-c-%"o tring,- @ C C-A == a!ove code !elongs to ;%; version !#teUV !#tes; O B 0/20$ 0/2I$ 0/e2 DA !#teUV !#tes2 O B 0/KL$ 0/aI DA charUV chars O new charUIVA Decoder d O Encoding%<"&L%5etDecoder,-A int charLen O d%5etChars,!#tes;$ 0$ !#tes;%Length$ chars$ 0-A == "he value of charLen should !e 2 now% charLen @O d%5etChars,!#tes2$ 0$ !#tes2%Length$ chars$ charLen-A foreach ,char c in charsConsole%'rite,C<@B0:*?D C$ ,ushort-c-A

Console%.eadEe#,-A D D

== Decoder class Class; B pu!lic static void Main,B string unicode tring O C"his string contains the unicode character 2i,Gu0Ia0-CA == Create two different encodings% Encoding ascii O Encoding%4 C11A Encoding unicode O Encoding%<nicodeA == Convert the string into a !#teUV% !#teUV unicode7#tes O unicode%5et7#tes,unicode tring-A == 2erform the conversion from one encoding to the other% !#teUV ascii7#tes O Encoding%Convert,unicode$ ascii$ unicode7#tes-A == Convert the new !#teUV into a charUV and then into a string%

== "his is a slightl# different approach to converting to illustrate == the use of 5etCharCount=5etChars% charUV asciiChars O new charUascii%5etCharCount,ascii7#tes$ 0$ ascii7#tes%Length-VA ascii%5etChars,ascii7#tes$ 0$ ascii7#tes%Length$ asciiChars$ 0-A string ascii tring O new string,asciiChars-A == Displa# the strings created !efore and after the conversion% Console%'riteLine,C6riginal string: B0DC$ unicode tring-A Console%'riteLine,C4scii converted string: B0DC$ ascii tring-A Console%.eadEe#,-A D D == tring .eader

private void !utton;\Clic0,o!3ect sender$ Event4rgs eB tring M# tring O te/t7o/;%"e/tA charUV M#Char O new charU;2VA tring.eader M# tring.eader O new M# tring.eader%.ead,M#Char$ 0$ 5-A foreach ,char c in M#Charla!el;%"e/t @O cA M# tring.eader%Close,-A tring.eader,M# tring-A

.eading trings private void !utton2\Clic0,o!3ect sender$ Event4rgs eB la!el;%"e/t O CCA string contents O te/t7o/;%"e/t%"rim,-A == C"est contentCA using , tring.eader reader O new tring.eader,contents-B int cA while ,,c O reader%.ead,-- YO 8;B la!el;%"e/t @O cA D D D 7inar# .eader and 7inar# 'riter private void !utton5\Clic0,o!3ect sender$ Event4rgs eB 7inar#'riter data6utA 7inar#.eader data1nA int i O ;0A dou!le d O ;%5>A !ool ! O trueA tr# B data6ut O new 7inar#'riter,new &ile tream,Ctestdata%t/tC$ &ileMode%Create--A D catch ,16E/ception e/cB Console%'riteLine,e/c%Message @ CGnCannot open file%C-A returnA D

tr# B ==Console%'riteLine,C'riting data6ut%'rite,i-A ==Console%'riteLine,C'riting data6ut%'rite,d-A ==Console%'riteLine,C'riting data6ut%'rite,!-A ==Console%'riteLine,C'riting data6ut%'rite,;2%2 M J%?-A

C @ i-A C @ d-A C @ !-A C @ ;2%2 M J%?-A

D catch ,16E/ception e/cB Message7o/% how,e/c%Message @ CGn'rite error%C-A D data6ut%Close,-A tr# B data1n O new 7inar#.eader,new &ile tream,Ctestdata%t/tC$ &ileMode%6pen--A D catch ,&ile)ot&oundE/ception e/cB Message7o/% how,e/c%Message @ CGnCannot open file%C-A returnA D tr# B i O data1n%.ead1ntI2,-A ==Console%'riteLine,C.eading C @ i-A la!el;%"e/t O i%"o tring,-A d O data1n%.eadDou!le,-A ==Console%'riteLine,C.eading C @ d-A la!el;%"e/t @O C C@d%"o tring,-A ! O data1n%.ead7oolean,-A ==Console%'riteLine,C.eading C @ !-A la!el;%"e/t @O C C @ !%"o tring,-A d O data1n%.eadDou!le,-A ==Console%'riteLine,C.eading C @ d-A la!el;%"e/t @O C C @ d%"o tring,-A D catch ,16E/ception e/cB Message7o/% how,e/c%Message @ C.ead error%C-A D D data1n%Close,-A

'hread5

4 thread is a separate se9uence of instructions designed for performing specific tas0 in the program% C# supports parallel e/ecution of code through multithreading% 4 thread is an independent e/ecution path$ a!le to run simultaneousl# with other threads%

@sing 'hreading 7# default$ a C# program has one thread% "his thread e/ecutes the code in the program starting and ending with the Main method% Ever# command e/ecuted !# Main88either directl# or indirectl#88is performed !# the default$ or primar# thread$ and this thread terminates when Main returns% :owever$ au/iliar# threads can !e created and used to e/ecute code in parallel with the primar# thread% "hese threads are often called worker!threads% 'or0er threads can !e used to perform time consuming or time critical tas0s without t#ing up the primar# thread% &or e/ample$ wor0er threads are often used in server applications to fulfill incoming re9uests without waiting

for the previous re9uest to !e complete% 'or0er threads are also used to perform C!ac0groundC tas0s in des0top applications so that the main thread88which drives user interface elements88remains responsive to user actions% Multithreading solves pro!lems with throughput and responsiveness$ !ut it can also introduce resource8 sharing issues such as deadloc0s and race conditions% Multiple threads are !est for tas0s that re9uire different resources such as file handles$ networ0 connections% 4ssigning multiple threads to a single resource is li0el# to cause s#nchroni+ation issues$ and having threads fre9uentl# !loc0ed while waiting for other threads defeats the purpose of using multiple threads% 4 common strateg# is to use wor0er threads to perform time8consuming or time8critical tas0s that don(t re9uire man# of the resources used !# other threads% )aturall#$ some resources in #our program must !e accessed !# multiple threads% &or these cases$ the #stem%"hreading namespace provides classes for s#nchroni+ing threads% "hese classes include Mute/$ Monitor$ 1nterloc0ed$ and 4uto.esetEvent$ and Manual.esetEvent% Nou can use some or all of these classes to s#nchroni+e the activities of multiple threads$ !ut some support for multi8threading is supported !# the C# language% &or e/ample$ the C# Loc0 tatement provides s#nchroni+ation features through implicit use of /onitor% 4 C# program starts in a single thread created automaticall# !# the CL. and operating s#stem ,the CmainC thread-$ and is made multi8threaded !# creating additional threads% :ere(s a simple e/ample and its output Multi threaded 2rogramming:8 "he 2rocess of developing a program for e/ecution with multiple threads is called multithreaded programming [ the process of e/ecution is called multithreading% imple thread 2rogram class "hread"est B static void Main,- B "hread t O new "hread ,'riteN-A t% tart,-A == .un 'riteN on the new thread while ,true- Console%'rite ,C/C-A == 'rite (/( forever D static void 'riteN,- B while ,true- Console%'rite ,C#C-A D ee the output == 'rite (#( forever

Compile and

"he main thread creates a new thread t on which it runs a method that repeatedl# prints the character *% imultaneousl#$ the main thread repeatedl# prints the character 9% "he CL. assigns each thread its own memor# stac0 so that local varia!les are 0ept separate% 1n the ne/t e/ample$ we define a method with a local varia!le$ then call the method simultaneousl# on the main thread and a newl# created thread: static void Main,- B new "hread ,5o-% tart,-A == Call 5o,- on a new thread 5o,-A ==Call 5o,- on the main thread D static void 5o,- B == Declare and use a local varia!le 8 (c#cles( for ,int c#cles O 0A c#cles S 5A c#cles@@- Console%'rite ,(T(-A D 6=2 TTTTTTTTTT "hreads share data if the# have a common reference to the same o!3ect instance% :ere(s an e/ample: class "hread"est B !ool doneA static void Main,- B "hread"est tt O new "hread"est,-A new "hread ,tt%5o-% tart,-A tt%5o,-A D == Create a common instance

== )ote that 5o is now an instance method

void 5o,- B if ,Ydone- B done O trueA Console%'riteLine ,CDoneC-A D D D 7ecause !oth threads call Bo67 on the same 'hread'est instance$ the# share the done field% "his results in CDoneC !eing printed once instead of twice: 6=2 : Done tatic fields offer another wa# to share data !etween threads% :ere(s the same e/ample with done as a static field: class "hread"est B static !ool doneA == tatic fields are shared !etween all threads static void Main,- B new "hread ,5o-% tart,-A 5o,-A D static void 5o,- B if ,Ydone- B done O trueA Console%'riteLine ,CDoneC-A D D D 7oth of these e/amples illustrate another 0e# concept Q that of thread!sa ety ,or$ rather$ lac0 of itY- "he output is actuall# indeterminate: it(s possi!le ,although unli0el#- that CDoneC could !e printed twice% 1f$ however$ we swap the order of statements in the Bo method$ then the odds of CDoneC !eing printed twice go up dramaticall#: static void 5o,- B if ,Ydone- B Console%'riteLine ,CDoneC-A done O trueA D D 6=2 Done Done ,usuall#Y"he pro!lem is that one thread can !e evaluating the if statement right as the other thread is e/ecuting the WriteLine statement Q !efore it(s had a chance to set done to true% "he remed# is to o!tain an e/clusive loc0 while reading and writing to the common field% C# provides the loc0 statement for 3ust this purpose: class "hread afe B static !ool doneA static o!3ect loc0er O new o!3ect,-A static void Main,- B new "hread ,5o-% tart,-A 5o,-A D static void 5o,- B loc0 ,loc0er- B if ,Ydone- B Console%'riteLine ,CDoneC-A done O trueA D D D

'hen two threads simultaneousl# contend a loc0 ,in this case$ lo )er-$ one thread waits$ or blocks$ until the loc0 !ecomes availa!le% 1n this case$ it ensures onl# one thread can enter the critical section of code at a time$ and CDoneC will !e printed 3ust once% Code that(s protected in such a manner Q from indeterminac# in a multithreading conte/t Q is called thread8safe% "emporaril# pausing$ or blocking$ is an essential feature in coordinating$ or synchroni(ing the activities of threads% 'aiting for an e/clusive loc0 is one reason for which a thread can !loc0% 4nother is if a thread wants to pause$ or leep for a period of time: "hread% leep ,"ime pan%&rom econds ,I0--A==7loc0 for I0seconds 4 thread can also wait for another thread to end$ !# calling its Xoin method: "hread t O new "hread ,5o-A == 4ssume 5o is some static method t% tart,-A t%Xoin,-A == 'ait ,!loc0- until thread t ends 4 thread$ while !loc0ed$ doesn(t consume C2< resources%

Jow 'hreading Wor)s Multithreading is managed internall# !# a thread!scheduler$ a function the CL. t#picall# delegates to the operating s#stem% 4 thread scheduler ensures all active threads are allocated appropriate e/ecution time$ and that threads that are waiting or !loc0ed Q for instance Q on an e/clusive loc0$ or on user input Q do not consume C2< time% 6n a single8processor computer$ a thread scheduler performs time)slicing!*!rapidl# switching e/ecution !etween each of the active threads% "his results in Cchopp#C !ehavior$ such as in the ver# first e/ample$ where each !loc0 of a repeating N or O character corresponds to a time8slice allocated to the thread% <nder 'indows *2$ a time8slice is t#picall# in the tens8of8milliseconds region Q chosen such as to !e much larger than the C2< overhead in actuall# switching conte/t !etween one thread and another ,which is t#picall# in the few8microseconds region-% 6n a multi8processor computer$ multithreading is implemented with a mi/ture of time8slicing and genuine concurrenc# Q where different threads run code simultaneousl# on different C2<s% 1t(s almost certain there will still !e some time8slicing$ !ecause of the operating s#stem(s need to service its own threads Q as well as those of other applications% 4 thread is said to !e preempted when its e/ecution is interrupted due to an e/ternal factor such as time8 slicing% 1n most situations$ a thread has no control over when and where it(s preempted% 'hreads "s4 ,ro esses 4ll threads within a single application are logicall# contained within a process Q the operating s#stem unit in which an application runs% "hreads have certain similarities to processes Q for instance$ processes are t#picall# time8sliced with other processes running on the computer in much the same wa# as threads within a single C# application% "he 0e# difference is that processes are full# isolated from each otherA threads share ,heap- memor# with other threads running in the same application% "his is what ma0es threads useful: one thread can !e fetching data in the !ac0ground$ while another thread is displa#ing the data as it arrives When to @se 'hreads 4 common application for multithreading is performing time8consuming tas0s in the !ac0ground% "he main thread 0eeps running$ while the worker!thread does its !ac0ground 3o!% 'ith 'indows &orms or '2& applications$ if the main thread is tied up performing a length# operation$ 0e#!oard and mouse messages cannot !e processed$ and the application !ecomes unresponsive% &or this reason$ itFs worth running time8consuming tas0s on wor0er threads even if the main thread has the user stuc0 on a W2rocessing_ please waitP modal dialog in cases where the program canFt proceed until a particular tas0 is complete% "his ensures the application doesnFt get tagged as W)ot .espondingP !# the operating s#stem$ enticing the user to forci!l# end the process in frustrationY "he modal dialog approach also allows for implementing a CCancelC !utton$ since the modal form will continue to receive events while the actual tas0 is performed on the wor0er thread% "he 7ac0ground'or0er class assists in 3ust this pattern of use% 1n the case of non8<1 applications$ such as a 'indows ervice$ multithreading ma0es particular sense when a tas0 is potentiall# time8consuming !ecause itFs awaiting a response from another computer ,such as an application server$ data!ase server$ or client-% :aving a wor0er thread perform the tas0 means the instigating thread is immediatel# free to do other things% 4nother use for multithreading is in methods that perform intensive calculations% uch methods can e/ecute faster on a multi8processor computer if the wor0load is divided amongst multiple threads% ,6ne can test for the num!er of processors via the En"ironment4,ro essorCount propert#-% 4 C# application can !ecome multi8threaded in two wa#s: either !# e/plicitl# creating and running additional threads$ or using a feature of the %)E" framewor0 that implicitl# creates threads Q such as 7ac0ground'or0er$ thread pooling$ a threading timer$ a .emoting server$ or a 'e! ervices or 4 2%)E" application% 1n these latter cases$ one has no choice !ut to em!race multithreading% 4 single8threaded 4 2%)E" we! server would not !e cool Q even if such a thing were possi!leY &ortunatel#$ with stateless application servers$ multithreading is usuall# fairl# simpleA one(s onl# concern perhaps !eing in providing appropriate loc0ing mechanisms around data cached in static varia!les% When Not to @se 'hreads Multithreading also comes with disadvantages% "he !iggest is that it can lead to vastl# more comple/ programs% :aving multiple threads does not in itself create comple/it#A it(s the interaction!between!the!threads that creates comple/it#% "his applies whether or not the interaction is intentional$ and can result long development c#cles$ as well as an ongoing suscepti!ilit# to intermittent and non8reproduca!le !ugs% &or this reason$ it pa#s to 0eep such interaction in a multi8threaded design simple Q or not use multithreading at all Q unless #ou have a peculiar penchant for re8writing and de!uggingY Multithreading also comes with a resource and C2< cost in allocating and switching threads if used e/cessivel#% 1n particular$ when heav# dis0 1=6 is involved$ it can !e faster to have 3ust one or two wor0ers thread performing tas0s in se9uence$ rather than having a multitude of threads each e/ecuting a tas0 at the same time% Creating and Starting 'hreads

"hreads are created using the 'hread classFs constructor$ passing in a 'hreadStart delegate Q indicating the method where e/ecution should !egin% :ereFs how the 'hreadStart delegate is defined: pu!lic delegate void "hread tart,-A Calling Start on the thread then sets it running% "he thread continues until its method returns$ at which point the thread ends% :ereFs an e/ample$ using the e/panded C# s#nta/ for creating a 'headStart delegate: class "hread"est B static void Main,- B "hread t O new "hread ,new "hread tart ,5o--A t% tart,-A == .un 5o,- on the new thread% 5o,-A == imultaneousl# run 5o,- in the main thread% D static void 5o,- B Console%'riteLine ,ChelloYC-A D ,assing !ata to 'hreadStart LetFs sa#$ in the e/ample a!ove$ we wanted to !etter distinguish the output from each thread$ perhaps !# having one of the threads write in upper case% 'e could achieve this !# passing a flag to the Bo method: !ut then we couldnFt use the 'hreadStart delegate !ecause it doesnFt accept arguments% &ortunatel#$ the %)E" framewor0 defines another version of the delegate called ,arameteri-ed'hreadStart$ which accepts a single o!3ect argument as follows: pu!lic delegate void 2arameteri+ed"hread tart ,o!3ect o!3-A "he previous e/ample then loo0s li0e this: class "hread"est B static void Main,- B "hread t O new "hread ,5o-A t% tart ,true-A == OO 5o ,true5o ,false-A D static void 5o ,object upperCase - B !ool upper O ,!ool- upperCaseA Console%'riteLine ,upper T C:ELL6YC : ChelloYC-A D 6=2 helloY :ELL6Y 1n this e/ample$ the compiler automaticall# infers a ,arameteri-ed'hreadStart delegate !ecause the 5o method accepts a single o!3ect argument% 'e could 3ust as well have written: "hread t O new "hread ,new 2arameteri+ed"hread tart ,5o--A t% tart ,true-A 4 feature of using ,arameteri-ed'hreadStart is that we must cast the o%&e t argument to the desired t#pe ,in this case %ool- !efore use% 4lso$ there is onl# a single8argument version of this delegate% 4n alternative is to use an anon#mous method to call an ordinar# method as follows: static void Main,- B "hread t O new "hread ,delegate,- B 'rite"e/t ,C:elloC-A D-A t% tart,-A D static void 'rite"e/t ,string te/t- B Console%'riteLine ,te/t-A D "he advantage is that the target method ,in this case 'rite"e/t- can accept an# num!er of arguments$ and no casting is re9uired% :owever one must ta0e into account the outer8varia!le semantics of anon#mous methods$ as is apparent in the following e/ample: static void Main,- B string te/t O C7eforeCA "hread t O new "hread ,delegate,- B 'rite"e/t ,te/t-A D-A te/t O C4fterCA t% tart,-A D static void 'rite"e/t ,string te/tB Console%'riteLine ,te/t-A D 6=2

4fter Note :8 4non#mous methods open the grotes9ue possi!ilit# of unintended interaction via outer varia!les if the# are modified !# either part# su!se9uent to the thread starting% 1ntended interaction ,usuall# via fields- is generall# considered more than enoughY 6uter varia!les are !est treated as read#8onl# once thread e/ecution has !egun Q unless one(s willing to implement appropriate loc0ing semantics on !oth sides% 4nother common s#stem for passing data to a thread is !# giving 'hread an instance method rather than a static method% "he instance o!3ectFs properties can then tell the thread what to do$ as in the following rewrite of the original e/ample: class "hread"est B !ool upperA static void Main,- B "hread"est instance; O new "hread"est,-A instance;%upper O trueA "hread t O new "hread ,instance;%5o-A t% tart,-A "hread"est instance2 O new "hread"est,-A instance2%5o,-A == Main thread Q runs with upperOfalse D void 5o,- B Console%'riteLine ,upper T C:ELL6YC : ChelloYC-A D Naming 'hreads 4 thread can !e named via its Name propert#% "his is of great !enefit in de!ugging: as well as !eing a!le to Console4WriteLine a threadFs name$ Microsoft Visual tudio pic0s up a threadFs name and displa#s it in the 'ebug! Location tool!ar% 4 threadFs name can !e set at an# time Q !ut onl# once Q attempts to su!se9uentl# change it will throw an e/ception% "he applicationFs main thread can also !e assigned a name Q in the following e/ample the main thread is accessed via the Current'hread static propert#: class "hread)aming B static void Main,- B "hread%CurrentThread.Name O CmainCA "hread wor0er O new "hread ,5o-A wor0er%Name O Cwor0erCA wor0er% tart,-A 5o,-A D static void 5o,- B Console%'riteLine ,C:ello from C @ "hread%Current"hread%)ame-A D D 6=2 :ello from main :ello from wor0er 'hread ,riorit* 4 threadFs ,riorit* propert# determines how much e/ecution time it gets relative to other active threads in the same process$ on the following scale: enum "hread2riorit# B Lowest$ 7elow)ormal$ )ormal$ 4!ove)ormal$ :ighest D "his !ecomes relevant onl# when multiple threads are simultaneousl# active% etting a threadFs priorit# to high doesnFt mean it can perform real8time wor0$ !ecause itFs still limited !# the applicationFs process priorit#% "o perform real8time wor0$ the ,ro ess class in S*stem4!iagnosti s must also !e used to elevate the process priorit# as follows ,1 didn(t tell #ou how to do this-: 2rocess%5etCurrent2rocess,-%2riorit#Class O 2rocess2riorit#Class%:ighA ,ro ess,riorit*Class4Jigh is actuall# one notch short of the highest process priorit#: Realtime% etting one(s process priorit# to Realtime instructs the operating s#stem that #ou never want #our process to !e preempted% 1f #our program enters an accidental infinite loop #ou can e/pect even the operating s#stem to !e loc0ed out% )othing short of the power !utton will rescue #ouY &or this reason$ Jigh is generall# considered the highest usa!le process priorit#% 1f the real8time application has a user interface$ it can !e undesira!le to elevate the process priorit# !ecause screen updates will !e given e/cessive C2< time Q slowing the entire computer$ particularl# if the <1 is comple/%

,4lthough at the time of writing$ the 1nternet telephon# program 0#pe gets awa# with doing 3ust this$ perhaps !ecause its <1 is fairl# simple-% Lowering the main threadFs priorit# Q in con3unction with raising the processFs priorit# Q ensures the real8time thread doesnFt get preempted !# screen redraws$ !ut doesnFt prevent the computer from slowing$ !ecause the operating s#stem will still allocate e/cessive C2< to the process as a whole% "he ideal solution is to have the real8time wor0 and user interface in separate processes ,with different priorities-$ communicating via .emoting or shared memor#% hared memor# re9uires 2=1nvo0ing the 'inI2 421 ,we!8search Create+ileMapping and Map&iew$ +ile-% E9 eption Jandling 4n# tr*M at hMfinall* !loc0s in scope when a thread is created are of no relevance once the thread starts e/ecuting% Consider the following program: pu!lic static void Main,- B tr# B new "hread ,5o-% tart,-A D catch ,E/ception e/- B == 'e(ll never get hereY Console%'riteLine ,CE/ceptionYC-A D D static void 5o,- B throw nullA D

"he tr*M at h statement in this e/ample is effectivel# useless$ and the newl# created thread will !e encum!ered with an unhandled NullReferen eE9 eption% "his !ehavior ma0es sense when #ou consider a thread has an independent e/ecution path% "he remed# is for thread entr# methods to have their own e/ception handlers: pu!lic static void Main,- B new "hread ,5o-% tart,-A D static void 5o,- B tr# B %%% throw nullA == this e/ception will get caught !elow %%% D catch ,E/ception e/- B "#picall# log the e/ception$ and=or signal another thread that we(ve come unstuc0 %%% D &rom %)E" 2%0 onwards$ an unhandled e/ception on an# thread shuts down the whole application$ meaning ignoring the e/ception is generall# not an option% :ence a tr*M at h !loc0 is re9uired in ever# thread entr# method Q at least in production applications Q in order to avoid unwanted application shutdown in case of an unhandled e/ception% "his can !e somewhat cum!ersome Q particularl# for 'indows &orms programmers$ who commonl# use the Cglo!alC e/ception handler$ as follows: using using using #stemA #stem%"hreadingA #stem%'indows%&ormsA

static class 2rogram B static void Main,- B 4pplication%"hreadE/ception @O :andleErrorA 4pplication%.un ,new Main&orm,--A D static void :andleError ,o!3ect sender$ "hreadE/ceptionEvent4rgs e- B Log e/ception$ then either e/it the app or continue%%% DD "he +ppli ation4'hreadE9 eption event fires when an e/ception is thrown from code that was ultimatel# called as a result of a 'indows message ,for e/ample$ a 0e#!oard$ mouse or CpaintC message- Q in short$ nearl# all code in a t#pical 'indows &orms application% 'hile this wor0s perfectl#$ it lulls one into a false sense of securit# Q that all e/ceptions will !e caught !# the central e/ception handler% E/ceptions thrown on wor0er threads are a good e/ample of e/ceptions not caught !# +ppli ation4'hreadE9 eption ,the code inside the /ain method is another Q including the main form(s constructor$ which e/ecutes !efore the 'indows message loop !egins-% "he %)E" framewor0 provides a lower8level event for glo!al e/ception handling: +pp!omain4@nhandledE9 eption% "his event fires when there(s an unhandled e/ception in an# thread$ and in an# t#pe of application ,with or without a user interface-% :owever$ while it offers a good last8resort mechanism for logging untrapped e/ceptions$ it provides no means of preventing the application from shutting down Q and no means to suppress the %)E" unhandled e/ception dialog%

'hreading in Windows 8orms 6ne of the issues which fre9uentl# comes up in newsgroups is how to handle threading in a <1% "here are two golden rules for 'indows &orms: ;- )ever invo0e an# method or propert# on a control created on another thread other than 1nvo0e$ 7egin1nvo0e$ End1nvo0e or Create5raphics$ and 1nvo0e.e9uired% Each control is effectivel# !ound to a thread which runs its message pump% 1f #ou tr# to access or change an#thing in the <1 ,for e/ample changing the "e/t propert#- from a different thread$ #ou run a ris0 of #our program hanging or mis!ehaving in other wa#s% Nou ma# get awa# with it in some cases$ !ut onl# !# !lind luc0% &ortunatel#$ the 1nvo0e$ 7egin1nvo0e and End1nvo0e methods have !een provided so that #ou can as0 the <1 thread to call a method for #ou in a safe manner% 2- )ever e/ecute a long8running piece of code in the <1 thread% 1f #our code is running in the <1 thread$ that means no other code is running in that thread% "hat means #ou won(t receive events$ #our controls won(t !e repainted$ etc% "his is a ver# 7ad "hing% Nou can e/ecute long8running code and periodicall# call 4pplication%DoEvents,-$ and this is the natural thing for man# V7 programmers to wish to do 8 !ut 1(d advise against it% 1t means #ou have to consider re8entranc# issues etc$ which 1 !elieve are harder to diagnose and fi/ than CnormalC threading pro!lems% Nou have to 3udge when to call DoEvents$ and #ou can(t use an#thing which might !loc0 ,networ0 access$ for instance- without ris0ing an unresponsive <1% 1 !elieve there are message pumping issues in terms of C6M o!3ects as well$ !ut 1 don(t have details of them ,and 1 fran0l# wouldn(t understand them full# an#wa#-% o$ if #ou have a piece of long8running code which #ou need to e/ecute$ #ou need to create a new thread ,or use a thread pool thread if #ou prefer- to e/ecute it on$ and ma0e sure it doesn(t directl# tr# to update the <1 with its results% "he thread creation part is the same as an# other threading pro!lem$ and we(ve addressed that !efore% "he interesting !it is going the other wa# 8 invo0ing a method on the <1 thread in order to update the <1% "here are two different wa#s of invo0ing a method on the <1 thread$ one s#nchronous ,1nvo0e- and one as#nchronous ,7egin1nvo0e-% "he# wor0 in much the same wa# 8 #ou specif# a delegate and ,optionall#- some arguments$ and a message goes on the 9ueue for the <1 thread to process% 1f #ou use 1nvo0e$ the current thread will !loc0 until the delegate has !een e/ecuted% 1f #ou use 7egin1nvo0e$ the call will return immediatel#% 1f #ou need to get the return value of a delegate invo0ed as#nchronousl#$ #ou can use End1nvo0e with the 14s#nc.esult returned !# 7egin1nvo0e to wait until the delegate has completed and fetch the return value% "here are two options when wor0ing out how to get information !etween the various threads involved% "he first option is to have state in the class itself$ setting it in one thread$ retrieving and processing it in the other ,updating the displa# in the <1 thread$ for e/ample-% "he second option is to pass the information as parameters in the delegate% <sing state somewhere is necessar# if #ou(re creating a new thread rather than using the thread pool 8 !ut that doesn(t mean #ou have to use state to return information to the <1% 6n the other hand$ creating a delegate with lots of parameters often feels clums#$ and is in some wa#s less efficient than using a simple Method1nvo0er or Event:andler delegate% "hese two delegates are treated in a special ,fast- manner !# 1nvo0e and 7egin1nvo0e% Method1nvo0er is 3ust a delegate which ta0es no parameters and returns no value ,li0e "hread tart-$ and Event:andler ta0es two parameters ,a sender and an Event4rgs parameter and returns no value% )ote$ however$ that if #ou pass an Event:andler delegate to 1nvo0e or 7egin1nvo0e then even if #ou specif# parameters #ourself$ the# are ignored 8 when the method is invo0ed$ the sender will !e the control #ou have invo0ed it with$ and the Event4rgs will !e Event4rgs%Empt#% :ere is an e/ample which shows several of the a!ove concepts% )otes are provided after the code% using using using using #stemA #stem%"hreadingA #stem%'indows%&ormsA #stem%DrawingA

pu!lic class "est : &orm B delegate void tring2arameterDelegate ,string value-A La!el status1ndicatorA La!el counterA 7utton !uttonA === Ssummar#H === Loc0 around target and currentCount === S=summar#H readonl# o!3ect stateLoc0 O new o!3ect,-A int targetA

int currentCountA .andom rng O new .andom,-A "est,B i+e O new i+e ,;L0$ ;20-A "e/t O C"estCA La!el l!l O new La!el,-A l!l%"e/t O C tatus:CA l!l% i+e O new i+e ,50$ 20-A l!l%Location O new 2oint ,;0$ ;0-A Controls%4dd,l!l-A l!l O new La!el,-A l!l%"e/t O CCount:CA l!l% i+e O new i+e ,50$ 20-A l!l%Location O new 2oint ,;0$ I?-A Controls%4dd,l!l-A status1ndicator O new La!el,-A status1ndicator% i+e O new i+e ,;00$ 20-A status1ndicator%Location O new 2oint ,J0$ ;0-A Controls%4dd,status1ndicator-A counter O new La!el,-A counter% i+e O new i+e ,;00$ 20-A counter%Location O new 2oint ,J0$ I?-A Controls%4dd,counter-A !utton O new 7utton,-A !utton%"e/t O C5oCA !utton% i+e O new i+e ,50$ 20-A !utton%Location O new 2oint ,;0$ 5L-A Controls%4dd,!utton-A !utton%Clic0 @O new Event:andler , tart"hread-A D void tart"hread ,o!3ect sender$ Event4rgs eB !utton%Ena!led O falseA loc0 ,stateLoc0B target O rng%)e/t,;00-A D "hread t O new "hread,new "hread tart,"hreadXo!--A t%1s7ac0ground O trueA t% tart,-A D void "hreadXo!,B Method1nvo0er updateCounterDelegate O new Method1nvo0er,<pdateCount-A int local"argetA loc0 ,stateLoc0B local"arget O targetA D <pdate tatus,C tartingC-A loc0 ,stateLoc0B currentCount O 0A D 1nvo0e ,updateCounterDelegate-A == 2ause !efore starting "hread% leep,500-A <pdate tatus,CCountingC-A for ,int iO0A i S local"argetA i@@B loc0 ,stateLoc0B currentCount O iA D

D <pdate tatus,C&inishedC-A 1nvo0e ,new Method1nvo0er,Ena!le7utton--A D void <pdate tatus,string valueB if ,1nvo0e.e9uiredB == 'e(re not in the <1 thread$ so we need to call 7egin1nvo0e 7egin1nvo0e,new tring2arameterDelegate,<pdate tatus-$ new o!3ectUVBvalueD-A returnA D == Must !e on the <1 thread if we(ve got this far status1ndicator%"e/t O valueA D void <pdateCount,B int tmpCountA loc0 ,stateLoc0B tmpCount O currentCountA D counter%"e/t O tmpCount%"o tring,-A D void Ena!le7utton,B !utton%Ena!led O trueA D static void Main,B 4pplication%.un ,new "est,--A D

== #nchronousl# show the counter 1nvo0e ,updateCounterDelegate-A "hread% leep,;00-A

D )otes:

tate is used to tell the wor0er thread what num!er to count up to% 4 delegate ta0ing a parameter is used to as0 the <1 to update the status la!el% "he wor0er thread(s principal method actuall# 3ust calls <pdate tatus$ which uses 1nvo0e.e9uired to detect whether or not it needs to Cchange threadC% 1f it does$ it then calls 7egin1nvo0e to e/ecute the same method again from the <1 thread% "his is 9uite a common wa# of ma0ing a method which interacts with the <1 thread8safe% "he choice of 7egin1nvo0e rather than 1nvo0e here was 3ust to demonstrate how to invo0e a method as#nchronousl#% 1n real code$ #ou would decide !ased on whether #ou needed to !loc0 to wait for the access to the <1 to complete !efore continuing or not% 1n practice$ 1 !elieve it(s 9uite rare to actuall# re9uire <1 access to complete first$ so 1 tend to use 7egin1nvo0e instead of 1nvo0e% 4nother approach might !e to have a propert# which did the appropriate invo0ing when necessar#% "hat(s easier to use from the client code$ !ut slightl# harder wor0 in that #ou would either have to have another method an#wa#$ or get the Method1nfo for the propert# setter in order to construct the delegate to invo0e% 1n this case we actuall# 0now that 7egin1nvo0e is! re9uired !ecause we(re running in the wor0er thread an#wa#$ !ut 1 included the code for the sa0e of completeness% 'e don(t call End1nvo0e after the 7egin1nvo0e% <nli0e all other as#nchronous methods ,see the later section on the topic- #ou don(t need to call End1nvo0e unless #ou need the return value of the delegate(s method% 6f course$ 7egin1nvo0e is also different to all of the other as#nchronous methods as it doesn(t cause the delegate to !e run on a thread pool thread 8 that would defeat the whole point in this caseY tate is used again to tell the <1 thread how far we(ve counted so far% 'e use a Method1nvo0er delegate to e/ecute <pdateCount% 'e call this using 1nvo0e to ma0e sure that it e/ecutes on the <1 thread% "his time there(s no attempt to detect whether or not an 1nvo0e is re9uired% 1 don(t !elieve there(s much harm in calling 1nvo0e or 7egin1nvo0e when it(s not re9uired 8 it(ll 3ust ta0e a little longer than calling the method directl#% ,1f #ou call 7egin1nvo0e it will have a different effect than calling the method directl# as it will occur later$ rather than in the current e/ecution flow$ of course%- 4gain$ we actuall# 0now that we need to call 1nvo0e here an#wa#%

4 !utton is provided to let the user start the thread% 1t is disa!led while the thread is running$ and another Method1nvo0er delegate is used to ena!le the !utton again afterwards% 4ll state which is shared !etween threads ,the current count and the target- is accessed in loc0s in the wa# descri!ed earlier% 'e spend as little time as possi!le in the loc0$ not updating the <1 or an#thing else while holding the loc0% "his pro!a!l# doesn(t ma0e too much difference here$ !ut 1 !elieve it(s worth getting into the ha!it of putting a loc0 around as little as possi!le 8 3ust as much as is needed% 1n particular$ it would !e disastrous to still have the loc0 in the wor0er thread when s#nchronousl# invo0ing <pdateCount 8 the <1 thread would then tr# to ac9uire the loc0 as well$ and #ou(d end up with deadloc0% "he wor0er thread is set to !e a !ac0ground thread ,1s7ac0groundOtrueA- so that when the <1 thread e/its$ the whole application finishes% 1n other cases where #ou have a thread which should 0eep running even after the <1 thread has 9uit$ #ou need to !e careful not to call 1nvo0e or 7egin1nvo0e when the <1 thread is no longer running 8 #ou will either !loc0 permanentl# ,waiting for the message to !e ta0en off the 9ueue$ with nothing actuall# loo0ing at messages- or receive an e/ception%

Beneri s5? 5enerics are a new feature in version 2%0 of the C# language and the common language runtime ,CL.-% 5enerics introduce to the %)E" &ramewor0 the concept of t#pe parameters$ which ma0e it possi!le to design classes and methods that defer the specification of one or more t#pes until the class or method is declared and instantiated !# client code% &or e/ample$ !# using a generic t#pe parameter " #ou can write a single class that other client code can use without incurring the cost or ris0 of runtime casts or !o/ing operations 4 simple e/ample 8 using 1ListS"H Most of the time #ou(re li0el# to !e using generics rather than writing #our own generic methods and t#pes% :ere(s a ver# simple e/ample to demonstrate the !enefits: using using #stemA #stem%Collections%5enericA

class "est B static void Main,B 1ListSstringH list O new ListSstringH,-A list%4dd,C:elloC-A list%4dd,C"hereC-A == 'ouldn(t compile 8 the list is strongl# t#ped$ == so there(s effectivel# onl# an 4dd,string- method == list%4dd,new o!3ect,--A == )o need for a cast here 8 again$ the list is == strongl# t#ped$ so the inde/er is of t#pe string% string / O listU0VA D D 5enerics 6verview <se generic t#pes to ma/imi+e code reuse$ t#pe safet#$ and performance% "he most common use of generics is to create collection classes% "he %)E" &ramewor0 class li!rar# contains several new generic collection classes in the #stem%Collections%5eneric namespace% "hese should !e used whenever possi!le in place of classes such as 4rra#List in the #stem%Collections namespace% Nou can create #our own generic interfaces$ classes$ methods$ events and delegates% 5eneric classes ma# !e constrained to ena!le access to methods on particular data t#pes% 1nformation on the t#pes used in a generic data t#pe ma# !e o!tained at run8time !# means of reflection%

7enefits of 5enerics 5enerics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generali+ation is accomplished !# casting t#pes to and from the universal !ase t#pe 6!3ect% 7# creating a generic class$ #ou can create a collection that is t#pe8safe at compile8time%

"he limitations of using non8generic collection classes can !e demonstrated !# writing a short program that ma0es use of the 4rra#List collection class from the %)E" &ramewor0 !ase class li!rar#% 4rra#List is a highl# convenient collection class that can !e used without modification to store an# reference or value t#pe% 5enerics in the .untime 'hen a generic t#pe or method is compiled into Microsoft intermediate language ,M 1L-$ it contains metadata that identifies it as having t#pe parameters% :ow the M 1L for a generic t#pe is used differs !ased on whether or not the supplied t#pe parameter is a value or reference t#pe% 'hen a generic t#pe is first constructed with a value t#pe as a parameter$ the runtime creates a speciali+ed generic t#pe with the supplied parameter or parameters su!stituted in the appropriate places in the M 1L% peciali+ed generic t#pes are created once for each uni9ue value t#pe used as a parameter% &or e/ample$ suppose #our program code declared a stac0 constructed of integers$ li0e this:C# tac0SintH stac0A 4t this point$ the runtime generates a speciali+ed version of the tac0S"H class with the integer su!stituted appropriatel# for its parameter% )ow$ whenever #our program code uses a stac0 of integers$ the runtime reuses the generated speciali+ed tac0S"H class% 1n the following e/ample$ two instances of a stac0 of integers are created$ and the# share a single instance of the tac0SintH code:C# tac0SintH stac06ne O new tac0SintH,-A tac0SintH stac0"wo O new tac0SintH,-A :owever$ if at another point in #our program code another tac0S"H class is created$ this time with a different value t#pe such as a long or a user8defined structure as its parameter$ the runtime generates another version of the generic t#pe$ this time su!stituting a long in the appropriate places in M 1L% Conversions are no longer necessar# !ecause each speciali+ed generic class nativel# contains the value t#pe% 5enerics wor0 a little differentl# for reference t#pes% "he first time a generic t#pe is constructed with an# reference t#pe$ the runtime creates a speciali+ed generic t#pe with o!3ect references su!stituted for the parameters in the M 1L% "hen$ each time a constructed t#pe is instantiated with a reference t#pe as its parameter$ regardless of what t#pe it is$ the runtime reuses the previousl# created speciali+ed version of the generic t#pe% "his is possi!le !ecause all references are the same si+e% &or e/ample$ suppose #ou had two reference t#pes$ a Customer class and an 6rder class$ and further suppose that #ou created a stac0 of Customer t#pes:C# class Customer B D class 6rder B D C# tac0SCustomerH customersA 4t this point$ the runtime generates a speciali+ed version of the tac0S"H class that$ instead of storing data$ stores o!3ect references that will !e filled in later% uppose the ne/t line of code creates a stac0 of another reference t#pe$ called 6rder:C# tac0S6rderH orders O new tac0S6rderH,-A

<nli0e with value t#pes$ another speciali+ed version of the tac0S"H class is not created for the 6rder t#pe% .ather$ an instance of the speciali+ed version of the tac0S"H class is created and the orders varia!le is set to reference it% uppose #ou then encountered a line of code to create a stac0 of a Customer t#pe:C# customers O new tac0SCustomerH,-A 4s with the previous use of the tac0S"H class created with the 6rder t#pe$ another instance of the speciali+ed tac0S"H class is created$ and the pointers contained therein are set to reference an area of memor# the si+e of a Customer t#pe% 7ecause the num!er of reference t#pes can var# wildl# from program to program$ the C# implementation of generics greatl# reduces code !loat !# reducing to one the num!er of speciali+ed classes created !# the compiler for generic classes of reference t#pes% Moreover$ when a generic C# class is instantiated with a t#pe parameter$ !e it a value or reference t#pe$ it can !e 9ueried at runtime using reflection and !oth its actual t#pe as well as its t#pe parameter can !e ascertained% 5enerics E/ample:8 private void 5enerics\Clic0,o!3ect sender$ Event4rgs eB la!el;%"e/t OCCA == M#Class5enerics is userdefined generics class which can accept !oth string == and int data t#pe

M#Class5enericsSstringH c; O new M#Class5enericsSstringH,-A c;%p O C"omCA c;%pp O CXers#CA M#Class5enericsSintH c2 O new M#Class5enericsSintH,-A c2%p O ;00A c2%pp O ;000A la!el;%"e/t O c;%pp @ C C @ c2%pp@ C C @ c;%p @ C C @ c2%pAA

Class file stored separatel# li0e this olution E/plorer 8H .ight clic0 8H add )ew 1tem 8H classname%cs class M#Class5enericsS"H B ==generic field private " m#fieldA private " m#field;A ==generics properties pu!lic " p B get B return m#fieldA D set B m#field O valueA D D pu!lic " pp B get B return m#field;A D set B m#field; O valueA D D D @sing List:; 5? private void !tn5enericsList\Clic0,o!3ect sender$ Event4rgs eB ListSstringH l O new ListSstringH,-A l%4dd,C;C-A l%4dd,C2C-A l%4dd,CIC-A l%4dd,C?C-A Displa#,l-A la!el;%Visi!le O trueA l%1nsert,I$ C5C-A Displa#,l-A !ool t O l%Contains,C2C-A Message7o/% how,t%"o tring,--A l%.emove,CIC-A Displa#,l-A Message7o/% how,CList )um!er in 2 C$ lU2V-A D private void Displa#,ListSstringH lB foreach ,string name in lB la!el;%"e/t @O name @ CGrGnCA D MM !i tionar* entr* using !i tionar*:; private void !tnDictionar#\Clic0,o!3ect sender$ Event4rgs eB la!el;%"e/t O CCA == #nta/

==Dictionar# St#pe argument8;$ t#pe argument82$H dOnew St#pe ==argument8;$t#pe argument82$H Dictionar#Sstring$ dou!leH d O new Dictionar#Sstring$ dou!leH,-A d%4dd ,CC8 harp 7oo0C$ ;25%25-A d%4dd ,C1nterview 7oo0C$ ;50-A d%4dd ,C'ro/ 4sp%netC$ 525%00-A foreach ,Ee#Value2airSstring$ dou!leH 0v in dB la!el;%"e/t @O 0v%Ee# @ C:C @ 0v%Value%"o tring ,- @ CGrGnCA D earchfor1tem ,d$ C1nterview 7oo0C-A earchfor1tem ,d$ CC8 harp 7oo0C-A D private void earchfor1tem ,Dictionar#Sstring$ dou!leH d$ string pB if ,d%ContainsEe#,p-la!el;%"e/t O p @ dUpVA D MM Lin)ed list private void !tnLin0edList\Clic0,o!3ect sender$ Event4rgs eB ==class Lin0edList)ode Lin0edListSstringH LL O new Lin0edListSstringH,-A LL%4dd&irst,C"omC-A LL%4dd4fter,LL%&irst$ CDic0C-A LL%4dd7efore,LL%Last$ CandC-A LL%4ddLast,Charr#C-A Displa#,LL-A Lin0edList)odeSstringH m#node O LL%&ind,C"omC-A Message7o/% how,CNour )ode : C @ m#node%Value-A D private void Displa#,Lin0edListSstringH lB foreach ,string name in lB la!el;%"e/t @O name @ CGrGnCA D D 'o understand iterators we first need to understand enumerators4 Enumerators are specialist o!3ects which provide one with the means to move through an ordered list of items one at a time ,the same 0ind of thing is sometimes called a `cursorF-% "he %)E" framewor0 provides two important interfaces relating to enumerators: 1Enumerator and 1Enumera!le% 6!3ects which implement 1Enumerator are themselves enumeratorsA the# support the following mem!ers: 8 the propert# Current$ which points to a position on the list 8 the method Move)e/t$ which moves the Current item one along the list 8 the method .eset$ which moves the Current item to its initial position ,which is !efore the first item-% 6!3ects which implement 1Enumera!le$ on the other hand$ merel# contract to provide enumerators when a re9uest is made to their 5etEnumerator method ,e/citingl#$ an o!3ect that implements !oth of these interfaces can return itself from the 5etEnumerator methodY#terators 1terators are a new feature in C# 2%0% 4n iterator is a method$ get accessor or operator that ena!les #ou to support foreach iteration in a class or struct without having to implement the entire 1Enumera!le interface% 1nstead$ #ou provide 3ust an iterator$ which simpl# traverses the data structures in #our class% 'hen the compiler detects #our iterator$ it will automaticall# generate the Current$ Move)e/t and Dispose methods of the 1Enumera!le or 1Enumera!leS"H interface% 1terators 6verview #mplementing iterators with *ield statements 1terators are ver# useful$ !ut in the past the#(ve !een a !it of a nuisance to write% )ot difficult as such$ !ut #ou(ve alwa#s needed an e/tra class in the past to store the state of where #ou(ve got up to in the collection$ etc% #ield statements allow #ou to write iterators CinlineC in a single method$ with the compiler doing all the hard wor0 of 0eeping trac0 of state !ehind the scenes%

#ield statements are onl# valid in a method=operator=propert# which returns one of 1Enumera!le$ 1Enumera!leS"H$ 1Enumerator or 1EnumeratorS"H% Nou can(t mi/ and match 8 if a mem!er uses #ield statements$ it can(t use normal return statements too% 1terators with a few restrictions Q Nou can(t put a #ield statment in a finall# !loc0% #ou can(t put a #ield return statement in a tr# !loc0 if there(s a catch !loc0% #ou can(t use unsafe code% :owever$ #ou can use normal looping$ access other varia!les etc% :ere(s an e/ample$ this time implementing 1Enumera!le: imple E/ample for 1terators : using #stemA using #stem%CollectionsA class "est B static void Main,stringUV argsB foreach ,string / in &oo,-B Console%'riteLine ,/-A D static 1Enumera!le &oo,B #ield return C:elloCA #ield return CthereCA D

4n iterator is a section of code that returns an ordered se9uence of values of the same t#pe% 4n iterator can !e used as the !od# of a method$ an operator$ or a get accessor% "he iterator code uses the #ield return statement to return each element in turn% #ield !rea0 ends the iteration% &or more information$ see #ield% Multiple iterators can !e implemented on a class% Each iterator must have a uni9ue name 3ust li0e an# class mem!er$ and can !e invo0ed !# client code in a foreach statement as follows: foreach,int / in ampleClass%1terator2-BD "he return t#pe of an iterator must !e 1Enumera!le$ 1Enumerator$ 1Enumera!leS"H$ or 1EnumeratorS"H% "he #ield 0e#word is used to specif# the value$ or values$ returned% 'hen the #ield return statement is reached$ the current location is stored% E/ecution is restarted from this location the ne/t time the iterator is called% 1terators are especiall# useful with collection classes$ providing an eas# wa# to iterate non8trivial data structures such as !inar# trees% using using using #stemA #stem%Collections%5enericA #stem%"e/tA

namespace Console\1terators\gene B class 2rogram B static void ample.everese,B intUV int4rra# O new intUV B 0$ ;$ 2$ I$ ?$ 5$ >$ J$ L$ K DA stringUV str4rra#O new stringUV B C+eroC$ ConeC$ CtwoC$CthreeC$CfourC$CfiveC DA Displa#4rra# ,int4rra#-A Displa#4rra# ,.everse ,int4rra#--A Displa#4rra# ,.everse ,str4rra#--A D static void Displa#4rra#S"H,1Enumera!leS"H displa#ed4rra#B &oreach ," item in displa#ed4rra#B Console%'rite ,CB0D C$ item-AD D static 1Enumera!leS"H .everseS"H,"UV original4rra#B for ,int i O original4rra#%Length 8 ;A i HO 0A i88-

6=2 0;2I?5>JLK KLJ>5?I2;0 &ive four three two one +ero

B #ield return original4rra#UiVA D static void Main,stringUV argsB 2rogram% ample.everese ,-A Console%.eadLine ,-A D DD

C# #terator E9ample pu!lic class Da#s6f"he'ee0 : 1Enumera!le B stringUV m\Da#s O B C unC$ CMonC$ C"ueC$ C'edC$ C"hrC$ C&riC$ C atC DA pu!lic #stem%Collections%1Enumerator 5etEnumerator,B for ,int i O 0A i S m\Da#s%LengthA i@@B #ield return m\Da#sUiVA D D

class "estDa#s6f"he'ee0 B static void Main,B == Create an instance of the collection class Da#s6f"he'ee0 wee0 O new Da#s6f"he'ee0,-A == 1terate with foreach foreach ,string da# in wee0B #stem%Console%'rite,da# @ C C-A D

D D

)ulla!le "#pe )ulla!le t#pes are instances of the #stem%)ulla!le struct% "he# can represent all the values of an underl#ing t#pe plus an additional null value% "he reason for using nulla!le t#pes is to overcome the issue of not !eing a!le to easil# determine if a value t#pe is empt# or undefined% <nli0e reference t#pes 8 which can !e assigned a null value 8 null is not assigna!le to primitive value t#pes% <se nulla!le t#pes as a consistent solution for determining whether a value t#pe is either empt# or undefined% Nulla%le logi !oolT has various !inar# logic operators$ !ut not all of the ones availa!le on !ool% 1mportantl#$ the CshortcutC operators ,[[ and ]]- aren(t defined for !oolT% 4 null value represents a sort of Cdon(t 0nowC value 8 so for instance$ null ] true is true$ !ut null ] false is nullA similarl# null [ false is false !ut null [ true is null% #stem%)ulla!leS"H varia!le)ameA ,,!method!"T varia!le)ameA ,,!method!.! 'here " is the underl#ing t#pe of the nulla!le t#pe% " can !e an# value t#pe including struct% &or e/ample: )ulla!leSintH i O nullA intT 3 O ;0A dou!leT d; O I%;?A !oolT flag O nullA charT letter O (a(A intTUV arr O new intTU;0VA Each instance of a nulla!le t#pe has two pu!lic read8onl# properties: JasValue 8 "#pe is !ool% "rue if the varia!le contains a non8null value% &or e/ample:

intT / O ;0A if ,/%:asValueB #stem%Console%'riteLine ,/%Value-A D else B #stem%Console%'riteLine ,C<ndefinedC-A D 7o/ing and <n!o/ing 'hen a nulla!le t#pe is !o/ed ,cast to a reference t#pe-$ onl# the value of the nulla!le t#pe is !o/ed% o if :asValue is true$ the value of Value is !o/ed% 1f :asValue is false$ a null reference is !o/ed% 'hen the resulting o!3ect is un!o/ed$ a new nulla!le t#pe is created$ and :asValue and Value are populated appropriatel#% "o convert a nulla!le t#pe !ac0 to the primitive t#pe on which it is !ased$ #ou can use the function #stem%)ulla!le%5etValue6rDefault,-% intT )ulla!le)um!er O nullA int )um!er O )ulla!le)um!er%5etValue6rDefault,-A == Default value is 0 )ulla!le)um!er O ;?>A )um!er O )ulla!le)um!er%5etValue6rDefault,-A == Value is ;?> :owever$ if #ou want to specif# #our own default value$ #ou can either specif# a default value or use the TT operator% "he TT operator will return the value if it is not null or the given value on the right side of the TT% intT )ulla!le)um!er O nullA int )um!er O )ulla!le)um!er%5etValue6rDefault,8;-A == )um!er is 8; )ulla!le)um!er O ;?>A )um!er O )ulla!le)um!er%5etValue6rDefault,8;-A == )um!er is ;?> == 1s the same as intT )ulla!le)um!er O nullA int )um!er O )ulla!le)um!er TT 8;A == )um!er is 8; )ulla!le)um!er O ;?>A )um!er O )ulla!le)um!er TT 8;A == )um!er is ;?>

C# Null-Coalescing Operator [Using?? ]


)ull Coalescing operator is a nice feature from %)et framewor0 2%0 onwards$ denoted with (TT(% "his can !e used on not onl# )ulla!le value t#pes !ut also with normal reference t#pe% 1f #ou would li0e to write precise piece of code this is the !est wa# to do it% "his ta0es two operands$ if the operand on left side is not null then it(s value will !e returned otherwise value from the right side operand will !e returned% Consider the e/ample 1ntI2T /2oint; O nullA =="his is e9ual to 1ntI2 a O ,/2oint YO null- T /2oint%Value : ;00 1ntI2 a O /2oint TT ;00A using #stemA class MainClass B static dou!le m#Method,- B Console%'riteLine,C1n m#Method,-%C-A return 0%0A D pu!lic static void Main,- B dou!leT defaultValue O ;%5A dou!le current7alanceA current7alance O defaultValue TT m#Method,-A Console%'riteLine,current7alance-A defaultValue O nullA current7alance O defaultValue TT m#Method,-A Console%'riteLine,current7alance-A

D D onst "s4 readonl* const and readonl# perform a similar function on data mem!ers$ !ut the# have a few important differences% onst 4 constant mem!er is defined at compile time and cannot !e changed at runtime% Constants are declared as a field$ using the const 0e#word and must !e initiali+ed as the# are declared% &or e/ampleA pu!lic class M#Class B pu!lic const dou!le 21 O I%;?;5KA D 21 cannot !e changed in the application an#where else in the code as this will cause a compiler error% Constants must !e of an integral t#pe ,s!#te$ !#te$ short$ ushort$ int$ uint$ long$ ulong$ char$ float$ dou!le$ decimal$ !ool$ or string-$ an enumeration$ or a reference to null% ince classes or structures are initiali+ed at run time with the new 0e#word$ and not at compile time$ #ou can(t set a constant to a class or structure% Constants can !e mar0ed as pu!lic$ private$ protected$ internal$ or protected internal% Constants are accessed as if the# were static fields$ although the# cannot use the static 0e#word% "o use a constant outside of the class that it is declared in$ #ou must full# 9ualif# it using the class name% readonl* 4 read onl# mem!er is li0e a constant in that it represents an unchanging value% "he difference is that a readonl# mem!er can !e initiali+ed at runtime$ in a constructor as well !eing a!le to !e initiali+ed as the# are declared% &or e/ample: pu!lic class M#Class B pu!lic readonl# dou!le 21 O I%;?;5KA D or pu!lic class M#Class B pu!lic readonl# dou!le 21A pu!lic M#Class,B 21 O I%;?;5KA D D 7ecause a readonl# field can !e initiali+ed either at the declaration or in a constructor$ readonl# fields can have different values depending on the constructor used% 4 readonl# field can also !e used for runtime constants as in the following e/ample: pu!lic static readonl# uint l; O ,uint-Date"ime%)ow%"ic0sA)otes readonl# mem!ers are not implicitl# static$ and therefore the static 0e#word can !e applied to a readonl# field e/plicitl# if re9uired% 4 readonl# mem!er can hold a comple/ o!3ect !# using the new 0e#word at initiali+ation% readonl# mem!ers cannot hold enumerations%

S-ar putea să vă placă și