C Sharp Basics
C Sharp Basics
doc 1 od 221
C Sharp Basics
Contents
243884333.doc 2 od 221
Authors
Introduction
Section I
1. Getting Started
2. Namespaces
3. Constructors and Destructors
4. Components and Databases
5. Web nab!ing Data
". #isce!!aneous
Section II
$. %unction &'er!oading and Inheritance
(. #odi)iers
*. +irtua! %unctions , ne-. o'erride
1/. 0roperties and Inde1ers
11. Inter)aces and Structures
12. &perator &'er!oading
13. Co!!ection &b2ects
14. Attributes. 3he 4e)!ection A0I and Conditiona!s
15. 5nsa)e code
Authors
+i2a6 #u7hi ([email protected]) is one o the pioneers o the !ndian !notech !ndustr". #or "ears$ he
has %een the irst to teach the emer&in& technolo&ies in !ndia thus ensurin& that !ndia al'a"s has
people trained in technolo&ies that the 'orld re(uires. )i*a" has 'ritten over 8+ %ooks on computers
and pro&rammin& over the last ei&ht "ears on su%*ects ran&in& rom C$ C,, (-he .d"sse" Series) to
Animation and /et'orkin& to 012. 3is ne'l" released %ook 45ava6Servlets65S27 has covered man"
aspects o 5ava in the most simpliied orm. )i*a" a%hors comple8ities and hence his %ooks sho'case
the most diicult concepts e8plained throu&h small pro&rams$ there%" &ivin& a &ood understandin&.
9icrosot:s ./et technolo&ies is 'hat )i*a" is no' ocussin& on and he aims at 'ritin& volumes on it.
Sandeep Shanbhag (sand".shan%ha&@vsnl.com) is a Chartered Accountant %" proession$ a technical
and inancial 'riter %" choice. ;nder the ae&is o <onderland !nvestment Consultants$ he has hitherto
%een 'ritin& re&ular columns or proessional *ournals$ 'e%sites and ne'spapers. Startin& out 'ith the
aim o levera&in& technolo&" to his domain kno'led&e o inance$ this is his irst steppin& stone.
Sona! #u7hi (svmukhi@"ahoo.com) is a reelance pro&rammer havin& a 'idespread
e8posure to computer techni(ues and lan&ua&es. Sonal has done &round%reakin& 'ork on
various !nternet -echnolo&ies like 5ava$ Active=$ 2erl and more. She has co6authored a e'
%ooks on computer pro&rammin& too.
243884333.doc 3 od 221
Introduction
<elcome to the irst installment on a series o 12 volumes dedicated to the latest technolo&" to hit the
third rock rom the sun. But %eore divin& in and &ettin& %oth eet 'et$ a 'ee %it o %ack&round.
9icrosot has al'a"s had a ha%it o doin& thin&s in st"le. <hether it 'as the %asic "et ro%ust >isk
.peratin& S"stem (>.S) or the (user6riendl"?) <indo's .peratin& S"stem$ 9icrosot has al'a"s
mana&ed to re'rite the rules in the computer 'orld. !n act it 'on:t %e e8a&&eration to sa" that toda" it
is thanks to the eorts o 9icrosot and the vision o its ounder$ Bill @ates$ that it is sot'are and not
machines$ that occup" centresta&e. But then that is another stor" altoðer.
/ot'ithstandin& its he&emon" over operatin& s"stems$ it must %e said that 9icrosot took its time to
'ake up to the call o the !nternet. /etscape 'as 'a" ahead in the race$ and !nternet 08plorer 'as a
distant ollo'er$ almost no'here in the reckonin&. 0ven as users had %e&un to 'rite o 9icrosot as a
non6starter or the 'e%$ it has &one and done 'hat he does %est 666pounced %ack 'ith technolo&" that
is more cuttin& ed&e than its peers.
Althou&h$ /etscape isn:t histor" as "et$ most people 'ould rather use a %ro'ser that 'orks %etter 'ith
the latest versions o <indo's. !nternet 08plorer literall" chooses itsel. -hen o course there are
other utilit" tools like 08cel$ <ord and 2o'er 2oint 6 all 9icrosot6o'ned and near6indispensa%le.
And no' 9icrosot has come out 'ith 9icrosot./et$ a pro*ect until recentl" called 9icrosot:s /e8t
@eneration <indo's Services architecture. -he o%*ective is the inte&ration o the !nternet 6 to oer
sot'are 6 like <ord and 08cel 6 throu&h "our %ro'ser on the computer as 'ell as on a ran&e o
devices such as the mo%ile phone and the personal di&ital assistant (2alm 2ilot etc).
-he &rand desi&n$ as it 'ere$ is to chan&e the ver" nature o the 'a" people 'ork presentl". -oda" 'e
&enerall" use one computer per person. Soon$ all 'e shall %e usin& 'ould %e onl" the !nternet. #or all
our needs. !n other 'ords$ 'henever "ou s'itch "our computer on$ "ou 'ould %e connected directl" to
the !nternet and not "our hard disk or even the most rudimentar" o tasks.
-he task is enormousA ever" packa&e no' on oer 'ill need additional code (even recodin&). !n the
ne' re&ime$ 9icrosot has &ot )isual Studio ./et 'hich can ena%le even the most uninitiated to
desi&n comple8 'e%sites provided o course one is 'e% and desi&n savv".
And all o this 'ill %e made possi%le throu&h a ne' pro&rammin& lan&ua&e called CB (pronounced C6
Sharp).
Wh6 C,Sharp8
<hen people talk o computer pro&rammin& lan&ua&es$ there is al'a"s a de%ate on 'hich one is
%etter. C,,$ 5ava$ 2erl$ 2323C the ar&uments and counter6points can %e endless. 3o'ever$ it is our
considered %elie that that CB 'ould %e in a sense %etter than the rest. And there is a reason or this.
/ormall"$ 'henever a ne' product is introduced$ it %etters the technolo&ies o its ilk. #or e8istin&
technolo&ies evolve 'ith their o'n pros and cons. -hereore$ in 1DDE$ 'hen Sun introduced 5ava$ it
took the %est rom amon&st all lan&ua&es and added current technolo&". /o' 9icrosot has done the
same. !ts taken the %est eatures rom C,, and 5ava and morphed them into this ne' pro&rammin&
lan&ua&e called CB.
!ma&ine those 'ho 'orked on 5ava 'hen it 'as launched si8 "ears a&o. -oda" a C) %oastin& o a si86
"ear e8perience in 5ava means the ma8imum possi%le. Simple arithmetic 6 5ava 'as launched onl" in
:DE. Similarl"$ i "ou &et into CB toda"$ onl" a 9icrosot en&ineer could have more 'orkin&
kno'led&e o itF -hereore$ 'e don:t think 'e need to ela%orate urther on the 'ei&ht that a C) 'ith
243884333.doc 4 od 221
CB e8posure 'ould commandF -hink or "oursel. Gou ma" kno' o people 'ho have struck luck" in
&ettin& a *o%. But 'hen it comes to keepin& it$ Had" Huck is po'erless.
!ndeed$ technolo&" is ruthless$ in that$ it %reaks across all a&e and seniorit" %arriers. -hat:s the reason
'h" even a teena&er could have as much e8perience 'ith a ne' technolo&" as a 4+6"ear6old. ;nair$
%ut true.
Who shou!d read this boo78
An"one 'antin& to %e on the cuttin& ed&e o ne' technolo&". -he %ook is 'ritten assumin& no prior
pro&rammin& kno'led&e on the part o the readers. 3o'ever$ 'e make certain other assumptions that
'e shall e8plain no'.
9an" a times$ on a clear ni&ht 'hen 'e look up at the stars$ 'e can:t help %ut 'onder 'hether there is
intelli&ent lie out there 6 or are the" *ust like us?
#or 'e don:t %elieve that intellect is a (ualit" that 'e are %orn 'ith. !n act 'e are &oin& to share a
secret 'ith "ou. !t is the secret o success &iven to us %" an old &"ps" 'oman. -his ma&ic mantra has
'orked 'ith man" and 'e assume "ou 'ould also use it in "our lie. !n act this is the onl"
assumption 'e make in this %ook.
-he secret is in persistence 6 nothin& in the 'orld can take place o persistence. -alent 'ill not$
nothin& is more common than unsuccessul people 'ith talent. @enius 'ill not$ unre'arded &enius is
almost a prover%. 0ducation 'ill not$ the 'orld is ull o educated derelicts. 2ersistence and
determination alone are omnipotent. <e hope "ou a&ree 'ith the old &"ps" appl" the ma8im 'hile
learnin& CB.
/o'$ the mere act that "ou are readin& this means that "ou are interested in learnin& somethin& ne'.
3o'ever$ there is a &reat deal o dierence %et'een a person 'ho 'ants to read a %ook and the person
'ho *ust 'ants a %ook to read. <e hope "ou %elon& to the ormer cate&or".
-hou&h 'e attempt to inuse a certain de&ree o humour in our 'ritin&$ please do not %u" this %ook or
its *okes. -his is no coee ta%le %ook or even %edtime readin&. -his is a %ook$ a medium$ 'hich 'e
hope 'ill do the serious *o% o teachin& the reader a ne' pro&rammin& lan&ua&e.
And ho' do 'e propose to &o a%out it? 5ust like 'hen "ou eat$ no matter ho' delicious the ood in
ront o "ou is$ "ou have to consume it$ one mouthul at a time. Gou *ust cannot eat it all at once$ can
"ou?
Similarl"$ 'hen learnin&$ it is al'a"s %etter to take small steps 6 one concept at a time. Sometimes$ 'e
even repeat the same concept several times$ in dierent 'a"s. #or 'e irml" %elieve that i "ou do the
little thin&s 'ell enou&h$ %i& thin&s 'ill come to "ou askin& to %e done.
!ncidentall"$ the entire CB sot'are is availa%le on the 9icrosot site$ do'nloada%le ree o char&e.
>etailed instructions are &iven on the site alon& 'ith a set o #AIs.
<ell$ that:s that. <e a&ree$ it is tou&h to clim% the ladder o success$ especiall" i "ou:re tr"in& to keep
"our nose to the &rindstone$ "our shoulders to the 'heel$ "our e"e on the %all and "our ear to the
&round. 2recisel" the reason 'h" some people do not reco&nise opportunit" 6 it oten comes dis&uised
as hard 'ork.
-his %ook presents "ou 'ith precisel" such an opportunit". <e hope "ou &ra% it 'ith %oth handsF
Ac7no-!edgements
243884333.doc E od 221
! 'ish to thank a num%er o people 'ho &ave me support$ ne' ideas and
inspiration throu&h the process o 'ritin& this %ook.
#irst and oremost$ thanks to #anish 9ain$ B2B pu%lication or pu%lishin& the %ook.
Special thanks to m" co6authors$ Sona! and Sandeep$ 'ho have put in their ver" %est in the 'ork
assi&ned to them as 'ithout them and their eorts the %ook 'ould have never seen the li&ht o da".
-hanks to m" cover desi&ners$ A!ta) :emani and ;ishore 4ohra$ or desi&nin& the cover in a ver"
short notice.
-hanks to #anish 0urohit or puttin& in late hours$ ormattin& and ali&nin& the te8t in the %ook.
-o$ 0radeep #u7hi and Shi'anand Shett6$ 'ho made it simple or me and m" co6authors to come
up 'ith the %ook.
A lon& list o riends and m" amil" need a mention here or their patience and cooperation on this
%ook 'hile it 'as %ein& 'ritten.
6Vijay Mukhi
Section I
1
@ettin& Started
CB is pronounced as JC sharpJ. !t is a ne' pro&rammin& lan&ua&e that ena%les pro&rammers in
(uickl" %uildin& solutions or the 9icrosot ./0- platorm.
-oda"$ one cannot$ *ust cannot$ aord to i&nore CB. !t is our considered opinion that it holds immense
promise and 'e are &oin& to tr" our %est$ throu&h this %ook$ to help "ou realiKe its potential. Be
assured$ 'e are not &oin& to teach "ou *ust another pro&rammin& lan&ua&e. !t is our intention to help
"ou appl" CB in practical situations$ to actuall" implement "our ne'l" ac(uired kno'led&e on the /et.
<ith this %rie introduction$ let us em%ark on a path that 'ill take "ou to ne' adventures in the 'orld
o !nternet. !n this chapter$ 'e 'ill &et "ou started 'ith CB %" introducin& a e' ver" simple pro&rams.
#or remem%er$ even a *ourne" o a thousand miles must %e&in 'ith a sin&le step.
<e assume that "ou have no prior kno'led&e o an" pro&rammin& lan&ua&e. But %eore 'e &et
ensnared in the ascinatin& 'orld o CB$ let:s make a director" 'here 'e 'ill save all our 'ork. !n
order to do so$ click on Start$ 2ro&rams$ then &o to Accessories and select Command 2rompt
(<indo's 2+++) or the 9S6>.S 2rompt as it is called in <indo's D8. .nce "ou are at the command
243884333.doc L od 221
prompt create a director" called csharp (md csharp) and chan&e to this director" (cd csharp). /o' t"pe
the command :edit a.cs:$ 'hich 'ill open the 9S6>.S editor 6 the 'orld:s simplest editor.
C:\csharp>edit a.cs
Ges$ 'e ver" 'ell understand ho' "ou must %e "earnin& to 'rite "our irst CB pro&ram and &et it
'orkin&. But %eore 'e do that$ there are certain intricacies that "ou must understand. <hat a.cs reers
to is called the ilename or pro&ram name. 3ere 'e have named our ile or pro&ram a.cs. <h" a.cs?
<ell$ %eore 'e %e&an 'ritin& this %ook$ 'e consulted a reno'ned astrolo&er 'ho predicted that i 'e
named our irst ile a.cs then &reat luck 'ould %e sho'ered on us. /ot 'antin& to (uarrel 'ith the
stars$ 'e named our ile a.cs. But "ou are ree to &o ahead and call "our ile an" name "ou 'ant. But
then do so at "our o'n riskF 1emem%er$ ore'arned is orearmedF
5okes aside$ :cs: is the e8tension used or CB iles. -he" sa" o all the thin&s "ou 'ear$ "our e8pression
is the most important. /ot'ithstandin& this$ one does look more dapper in a suit rather than a vapid
shirt and trousers. Similarl"$ thou&h it is not mandator" to provide the e8tension :cs:$ "ou can make a
ilename seem more impressive %" &ivin& it an e8tension. -o reiterate$ "ou could have &iven the
e8tension sa" :'s: tooM it does not matter. But a%sent minded as 'e are$ it is more prudent to &ive
appropriate e8tensions 'hile namin& iles.
As the irst step$ 'e 'ill understand the %asic structure o a CB pro&ram.
a.cs
class zzz
{
}
3ere 'e start 'ith the 'ord class KKK ollo'ed %" open and close curl" %races. A class is nothin& %ut a
collection 666 a collection o ever"thin& that the pro&rammin& lan&ua&e contains. !t is like a packet or a
container$ 'hich can hold an"thin&. 3ence ever"thin& in a C< program must be enc!osed -ithin a
c!ass. <e have named our class KKK$ a&ain "ou could have named it an"thin& else %ut i "ou 'ould
rather ollo' our namin& convention (or reasons 'ell ampliied a%oveF)$ name it KKK.
/o' or the part that "ou:ve %een ea&erl" 'aitin& orF
!n order to e8ecute the pro&ram$ &o to the #ile menu$ and click on 08it. Gou 'ill &et a dialo& %o8
askin& "ou 'hether "ou 'ant to save the ile or not$ sa" "es. /o' that 'e have t"ped and saved our
ile 'e need to e8ecute it. -he compiler creates e8ecuta%le code. -he command used to call the CB
compiler is csc ollo'ed %" the pro&ram name. Since our pro&ram name is a.cs$ the command csc a.cs
'ill call the compiler. A compiler is a pro&ram 'hich understands the CB pro&rammin& lan&ua&e.
-hus the 'ord class is part and parcel o the CB lan&ua&e. 9icrosot lets "ou reel" do'nload the CB
compiler rom their 'e% site A httpANNmsdn.microsot.comNli%rar"Ndeault.asp. Select ./et #rame'ork
S>O under ./0- >evelopment. Choose the >o'nload option to do'nload the sdk 'hich is around
12P 9B lar&e. !nstall the product on "our machine cause i "ou don7t$ none o the ollo'in& pro&rams
'ill 'ork. Also$ !nternet 08plorer E.E and 9icrosot >ata Access Components(2.P) must %e installed
prior to installin& the sdk
.nce done$ t"pe the command as ollo'sA
C:\csharp>csc a.cs
Gou 'ill see the ollo'in& output on "our screen in the dos %o8.
Microsoft (R) Visual C# Compiler Version 7.00.9!" #C$R %ersion %&.0.9&"' Cop(ri)ht (C)
Microsoft Corp 000*00&. +ll ri)hts reser%ed.
243884333.doc P od 221
error C,!00&: -ro)ram .a.e/e0 does not ha%e an entr( point defined
5ust as the e8citement 'as %e&innin& to &ro'$ our pro&ram returns 'ith an error messa&e. >on:t 'orr"$
occasional ailure is the price o improvement.
-he error messa&e starts 'ith an error num%er CSE++1 ollo'ed %" a cr"ptic messa&e$ 'hich 'e do
not understand.
<e are a'are o the act that ever"thin& has a %e&innin& and an end. Similarl"$ a CB pro&ram also has
a start and an end. AhF /o' "ou realiKe 'h" the error occurred. We )orgot to te!! C< -here to start
e1ecuting our program )rom. 3his starting point is a!so ca!!ed an entr6 point.
=ou can speci)6 the entr6 point b6 adding static 'oid #ain>? to "our pro&ram$ *ust as 'e have done
%elo'.
a.cs
class zzz
{
static void Main()
{
}
}
Compile the a%ove code &ivin& the command as csc a.cs. )oilaF /o' no errors.
-he compiler 'ill no' &enerate an e8e ile called a.e8e. @ivin& the command dir at the command
prompt 'ill prove the same. .n keen o%servation "ou 'ill notice that amon& the 2 iles listed$ there is
a ile %" the name a.e8e. Simpl" t"pe :a: at the command prompt$ "our pro&ram 'ill no' %e e8ecutedF
C:\csharp>a
-he pro&ram 'ill run %ut sho's no output on our screen. But$ at least 'e &et no errors.
-he 'ords$ static and void$ 'ill %e e8plained to "ou a little later$ in the ri&ht perspective. -hus i "ou
had elt the %e&innin&s o a massive headache$ "ou can %reathe eas"@ An6thing )o!!o-ed b6 A>A and
A?A brac7ets is ca!!ed a )unction. So$ it is o%vious that 9ain is nothin& %ut a unction. 3ere 'e are
creatin& a unction called 9ain. !t is ollo'ed %" the :Q: and :R: curl" %races. /ote that the letter 9 in
9ain is capital. -hus C< reBuires a )unction ca!!ed #ain. -hich is the )irst )unction that -i!! be
e1ecuted. #ailure to do so 'ill result in an error. 0r&o$ 'henever "ou see a 'ord %e&innin& 'ith an
open :(: and close %racket :):$ CB and most other pro&rammin& lan&ua&es call it a unction. 3he
C signi)ies the start o) a )unction and the D signi)ies the end o) the )unction. -he &u"s 'ho desi&ned
the lan&ua&e decided to use QR %races instead o start and end. <hen "ou tell people that "ou are
learnin& a pro&rammin& lan&ua&e$ "ou are actuall" learnin& to use QR %races to speci" the %e&innin&
and end o a unction. -hese rules have to %e remem%ered %" rote. Gou have no choice.
/o' 'e are read" to add some code in our pro&ram. !n order to do so$ add the line <riteHine(J3ellJ)$
*ust as 'e have done %elo'.
a.cs
class zzz
{
static void Main()
{
WriteLine("Hell")
}
}
243884333.doc 8 od 221
.opsF -he astrolo&er had promised sho'ers o luckF 0ven a driKKle seems ar a'a"F 08ecutin& the
a%ove pro&ram results in the ollo'in& errorA
Compiler 1rror
a.cs(!2&3): error C,&00: 4 e/pected
-he error messa&e %e&ins 'ith the ile name$ a.cs ollo'ed %" round %rackets containin& the line
num%er and the column num%er$ 'here the error occurred. -he compiler inorms us that it ound an
error on line num%er E and column num%er 18 and it e8pects a M.
As the clichS &oes$ 'hen the &oin& &ets tou&h$ the tou&h &et &oin&. So 'e shouldn:t lose heart as "etM
let:s understand 'h" this error occurred.
Hook at <riteHine 'ithin the %racketsM doesn:t it rin& a %ell? !sn:t <riteHine a unction too? But here
'e do not have the curl" %races ollo'in& it. -his is %ecause here 'e are not creatin& a unction like
'e created 9ain. -hen 'hat is it that 'e are doin&? <e are callin& a unction called <riteHine$ 'hich
has alread" %een created.
-he error sa"s :M: e8pected. -hou&h it is o%vious to us that the statement has ended$ unortunatel" or
"ou and me$ CB isn:t so smart. !t reBuires a semi,co!on to te!! it !oud and c!ear that the statement
has ended. 9erel" pressin& enter does not suice. -hou&h not so or other pro&rammin& lan&ua&es$
in CB it is mandator" to use a semi6colon. AlasF 0ach pro&rammin& lan&ua&e has its o'n rulesF
At this *uncture$ an intelli&ent (uestion 'ould %e 6 But 'h" semi6colon? <h" not an" other
punctuation mark? <e don:t kno' or sure %ut perhaps the developers o CB 'ere asked to select a
character that 'ould indicate the end o a statement. -he non6compromisin& species that 'e are$ the"
could not arrive at a consensus. 1esult? @randma:s recipe o eene meene mina moF <hen the"
stopped$ their in&er 'as pointin& at the semi6colon$ hence the" selected the same.
-hus rules are rulesM as preposterous as the" ma" sound$ the" must %e ollo'ed.
Add the semi6colon and e8ecute the pro&ram. Also lan&ua&es like ABA2N4 rom SA2 ends lines 'ith a
dot (ull stop). -hus 'e e8pect to understand pro&rammin& in 0n&lish. 0ver" lan&ua&e e8pects an end
o statementNcommand terminator. 0ver" lan&ua&e e8pects a s"m%ol to denote 'hen the user has
inished sa"in& somethin&. !n CB it is a M $ other lan&ua&es have their o'n s"m%ols. 1emem%er that the
statement or unction <riteHine 'as 'ritten on line num%er E hence the error reported line num%er E.
a.cs
class zzz
{
static void Main()
{
WriteLine("Hell");
}
}
Compiler 1rror
a.cs(!2&): error C,0&05: 6he name 78rite$ine7 does not e/ist in the class or namespace 79997
Another errorF <e are e8tremel" disappointed$ it *ust doesn:t seem our da". 3o'ever 'e irml" %elieve
that "ou ma" %e disappointed i "ou ail$ %ut are surel" doomed i "ou don:t tr". And 'e don:t 'ant to
%e doomed do 'e? So let:s keep our chin up and carr" on.
But "ou kno' 'hat:s most irritatin&l" %othersome? <h" are all error messa&es so diicult to
understand? <ell$ 'ith the e8perience that 'e have &ained over the "ears 'e have learnt that i error
messa&es could %e understood then 'e 'ouldn:t &et them in the irst placeF
243884333.doc D od 221
!n an" case$ to %e trul" candid$ the error occurred %ecause 'e pulled a ast one on "ouF <e are callin&
a unction <riteHine %ut in act no such unction e8ists. -he accurate name o the unction is not
<riteHine %ut S"stem.Console.<riteHine. 9icrosot is kno'n to anc" %i& names and here is one
more e8ample. !n an" case$ let:s e8ecute the pro&ram.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("Hell");
}
}
:utput
;ell
#inall"$ no errorsF Surel" "ou eel %lessedF !t displa"s the 'ord :3ell:$ and 'e suspect that:s e8actl"
'hat "ou are &oin& throu&h ri&ht no'. But i "ou ollo' our pro&rams step %" step 'e assure "ou that
heaven is not too ar a'a".
/o' remove all the e8tra spaces and :enters: rom "our pro&ram$ *ust as 'e have done %elo' and
compile the pro&ram a&ain.
a.cs
class zzz {static void Main() {System.Console.WriteLine("Hell");}}
:utput
;ell
Gou 'ill notice that doin& so does not &ive an" errors. 5ust like the previous pro&ram$ it displa"s :3ell:.
-he CB compiler is not aected %" it. But usin& spaces and :enters: deinitel" make "our pro&ram
neater and there%" more reada%le. -he eect is especiall" appreciated in lar&e pro&rams and more so
'hen someone else has to &o throu&h them. 3avin& said that$ an"'a"$ the irst thin& that CB compiler
does is removes all the spaces and enters rom the pro&ram code "ou have 'ritten.
!n the ne8t pro&ram$ 'e have called <riteHine unction t'ice.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("Hell");
System.Console.WriteLine("Bye");
}
}
:utput
;ell
<(e
.n e8ecutin& this pro&ram$ :3ell: and :B"e: are displa"ed on t'o separate lines. 3ere$ 'e are not
re(uired to &ive an"thin& that has the :enter: eect$ <riteHine automaticall" prints on a ne' line each
time. <hich simpl" means "ou can call a unction as man" times as "ou like.
243884333.doc 1+ od 221
!n the ne8t illustration$ let:s understand ho' unctions are called and created. 3ere 'e are callin& a
unction a%c().
a.cs
class zzz
{
static void Main()
{
abc();
}
}
Compiler 1rror
a.cs(!2&): error C,0&05: 6he name 7a=c7 does not e/ist in the class or namespace 79997
.n e8ecutin& this pro&ram "ou 'ill &et$ 'hat else$ %ut an error. 2eter >rucker$ the amed mana&ement
&uru had once said that the %etter a man is$ the more mistakes he 'ill make$ or the more ne' thin&s
he 'ill tr". So there "ou &o 6 ne8t time "ou encounter an error$ simpl" tell "oursel that "ou have *ust
%ecome %etter at 'hatever "ou are doin&.
!n an" case$ the error sa"s that a%c does not e8ist. 3ere 'e are callin& a unction called a%c()$ %ut
'here is a%c() deined or created ? !t is not a unction that has %een provided %" CB to us ree o
char&e. !t is our o'n home&ro'n unction that 'e are callin&. -he lesson here is that 'e cannot call a
unction 'ithout irst creatin& it. So$ to recti" this error 'e 'ill irst create a unction a%c. .ur ne8t
e8ample demonstrates this.
a.cs
class zzz
{
static void Main()
{
abc();
}
static void abc()
{
System.Console.WriteLine ("Hell");
}
}
:utput
;ell
!n the unction a%c$ 'e have included onl" one statement6 <riteHine 'ithin the curl" %races. 3he ACA
and ADA braces indicate the beginning and the end o) this )unction. Alternativel"$ a unction can
contain millions o lines o code that 'ill %e e8ecuted 'hen the unction is called. Since e'er6thing is
contained in a c!ass. our )unction abc is a!so created -ithin the c!ass EEE but outside #ain. But
the unction is called rom 9ain. .n e8ecutin& the pro&ram$ :3ell: is displa"ed. -his is %ecause 'e
have included the code or :3ell: to %e displa"ed in the unction a%c. -hus$ 'hen the control reaches
the line a%c()M it searches or that unction and e8ecutes the code 'ithin that unction. <e 'ill e8plain
static and void later as promised.
Gou can call as man" unctions as "ou like rom "our pro&ram. But "ou must remem%er to separate
each one 'ith a semi6colon. -he ne8t pro&ram illustrates this.
a.cs
class zzz
{
static void Main()
243884333.doc 11 od 221
{
abc();
!r();
abc();
}
static void abc()
{
System.Console.WriteLine ("" am #BC");
}
static void !r()
{
System.Console.WriteLine ("" am $%& ");
}
}
:utput
> am +<C
> am -?R
> am +<C
At irst the unction a%c is called$ then p(r and then a&ain 'e are callin& a%c. .n e8ecutin& this
pro&ram :! am ABC:$ :! am 2I1: and :! am ABC: 'ill %e displa"ed. -his is %ecause 'e have included
the code or these lines to %e displa"ed in the respective unctions.
!n the ollo'in& pro&ram 'e are callin& the unction p(r rom a%c and not rom 9ain.
a.cs
class zzz
{
static void Main()
{
abc();
}
static void abc()
{
!r();
System.Console.WriteLine ("" am #BC");
}
static void !r()
{
System.Console.WriteLine ("" am $%& ");
}
}
:utput
> am -?R
> am +<C
!n the unction a%c$ 'e are irst callin& p(r and then displa"in& :! am ABC: usin& the <riteHine
unction. 3ence$ irst :! am 2I1: is displa"ed and then :! am ABC:. -hus$ this pro&ram demonstrates
ho' unctions can %e called rom other unctions.
/o' that 'e have created our o'n unctions a%c and p(r$ 'e have an intuitive understandin& o ho'
CB created the unction S"stem.Console.<riteHine. -he ne8t pro&ram uses the printin& or ormattin&
capa%ilities o the <riteHine unction.
a.cs
class zzz
243884333.doc 12 od 221
{
static void Main()
{
System.Console.WriteLine("'(( {(}")'(();
}
}
:utput
&00 &00
-he Kero in the curl" %races means that ater the irst comma there is some value and that it should
displa" this value. Gou cannot dierentiate %et'een the t'o 1++:s. -he Q+R is replaced 'ith 1++$ the
num%er$ 'hich ollo's the irst comma. ! "ou don:t like the num%er 1++$ use the num%er 42+ instead.
<e 'on:t mind 6 at least it:s somethin& that some o "ou can easil" identi" 'ithF
-he pro&ram %elo' is simpl" an e8tension o the a%ove.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("'(( {(}){'}")'(()*(();
}
}
:utput
&00 &00200
3ere the Q+R is replaced 'ith 1++ and Q1R is replaced 'ith 2++. -he comma ($) separates the t'o
num%ers. -hus Q+R means the irst num%er and Q1R means the second. CB likes to count rom Kero and
not one.
a.cs
class zzz
{
static void Main()
{
ii;
ii+*(;
System.Console.WriteLine ("{(}")ii);
}
}
Compiler 1rror
a.cs(!2&): error C,00&: :nl( assi)nment2 call2 increment2 decrement2 and ne@ e/pressions
can =e used as a statement
a.cs(!2&): error C,0&05: 6he name 7ii7 does not e/ist in the class or namespace 79997
a.cs(A2&): error C,0&05: 6he name 7ii7 does not e/ist in the class or namespace 79997
a.cs(7255): error C,0&05: 6he name 7ii7 does not e/ist in the class or namespace 79997
08perience is kno'in& a lot more o thin&s "ou shouldn:t. But no' that "ou have decided to em%ark
upon this %ook$ let:s see 'hat "ou should kno'FF 08ecutin& this pro&ram results in a lar&e num%er o
errors as sho'n a%ove. Het:s understand the rationale %ehind it. 3ere 'e have included a stran&e 'ord
666 ii. -his 'ord ii is %ein& &iven a value o 2+ as iiT2+. But CB is a sh" pro&ram. !t does not speak to
stran&ersF 3ere ii is nothin& %ut a stran&er to CB. CB does not kno' 'ho or 'hat ii is. Gou can:t *ust
'rite 'ords that "ou eel &ood a%out. So$ in order to recti" this error 'e must tell CB 'ho ii is.
243884333.doc 13 od 221
.ur ne8t pro&ram 'ill demonstrate ho' this can %e done.
a.cs
class zzz
{
static void Main()
{
int ii;
ii+*(;
System.Console.WriteLine ("{(}")ii);
}
}
:utput
0
/ote that in this pro&ram 'e have added the 'ord int %eore ii. -he 'ord int indicates that ii is an
inte&er or a num%er. 0ach time 'e create our o'n 'ord like ii$ CB 'ants to kno' 'hat 'e 'ill store in
this 'ord. <e 'ill understand this %etter and in totalit" in *ust a little 'hile. 3ere 'e are initialiKin& ii
to 2+ or &ivin& it a value o 2+ %" 'ritin& ii T 2+. <h" 2+? 9a"%e %ecause 'e are eelin& ver"
"outhul toda"F #ollo'in& this 'e have the <riteHine unction. /o'$ it is a kno'n act that *a&&er" is
a &ood su%stitute or su&ar. Similarl"$ in CB "ou can su%stitute a num%er 'ith a 'ord. So$ in <riteHine
'e have used the 'ord ii instead o a num%er. -he 'ord ii &ets replaced 'ith the value 2+. So$ on
e8ecutin& the pro&ram$ the num%er 2+ is displa"ed.
Gou ma" %e 'onderin& as to 'h" should "ou ever use a 'ord 'hen "ou can use a num%er directl".
.ur ne8t pro&ram 'ill enli&hten "ou on this.
a.cs
class zzz
{
static void Main()
{
int ii;
ii+*(;
System.Console.WriteLine ("{(}")ii);
ii+,(;
System.Console.WriteLine ("{(}")ii);
ii+ii-'(;
System.Console.WriteLine ("{(}")ii);
ii+ii-';
System.Console.WriteLine ("{(}")ii);
ii--;
System.Console.WriteLine ("{(}")ii);
}
}
:utput
0
50
"0
"&
"
-he irst three lines o this pro&ram are identical to those o our previous one. -hus in the irst$ the
<riteHine unction 'ill displa" the num%er 2+. -hereater$ %" sa"in& iiT3+ 'e are initialiKin& the 'ord
ii to a value 3+. !n eect$ 'e are chan&in& the value o ii rom 2+ to 3+. So$ <riteHine 'ill no'
displa" 3+.
243884333.doc 14 od 221
#or conceptual understandin&$ 'e earlier introduced ii as a 'ord. 3o'ever$ in the sot'are 'orld$ it
has another nameM it is actuall" called a varia%le.
-hus$ a varia%le is a 'ord 'hose value varies or chan&es. ii initiall" had a value 2+ that chan&ed to
3+.
Comin& %ack to 'hat the 'ord int means6 'hen "ou sa" int$ int means inte&er or num%er. <hen 'e
sa" int ii$ it means that the varia%le ii 'ill store a num%er. ii could also %e used to store the letters o
the alpha%et like the names o people. !t could also store a date. But here 'e 'anted ii to store a
num%er. So$ 'e have to tell CB in advance as to 'hat the varia%le is &oin& to store. 3ence 'e sa" int ii.
CB understands the 'ord int as int is a part o the CB pro&rammin& lan&ua&e.
-he varia%le ii started 'ith the value 2+ and is no' holdin& a value 3+. !n the ne8t line 'e have
iiTii,1+. -he :e(ual to: si&n makes this statement look complicated. -o avoid conusion$ al'a"s start
%" lookin& to the ri&ht o the :e(ual to: si&n. -o the ri&ht o the e(ual to si&n 'e have ii,1+. Since ii is
holdin& the value 3+$ ii,1+ is read as 3+,1+$ 'hich evaluates to 4+. 3ence iiTii,1+ 'ill no' %e read
as iiT4+. -his value 4+ is &iven to the varia%le on the let6hand side. /o' that ii has a value 4+$
<riteHine 'ill displa" 4+. Similarl"$ 'e sa" iiTii,1. 3ere the value o ii is incremented %" one. And
the ne' value o ii$ 'hich is 41 'ill %e displa"ed %" <riteHine. !n the ne8t line 'e have ii,,. /ote
that iiTii,1 and ii,, do the same thin&. -he" %oth increment the value o ii %" 1. 3ence <riteHine 'ill
no' print the num%er 42.
-his is a %i& pro%lem 'ith pro&rammin& lan&ua&es. As there are man" 'a"s to skin a cat$ there are
also man" 'a"s to increase the value o a varia%le. So ii T ii , 1 and ii,, do the same thin&.
A pro&rammer thus has the choice to use either o the t'o 'a"s to do the same thin&. -here "ou &o
666as "ou can see$ irst time pro&rammers have unortunatel" a lot to learn.
!n dail" lie$ a hundred dierent people can do the same chore in a hundred dierent 'a"s. Similarl"$
in pro&rammin& there is more than one 'a" o doin& a particular thin&. 2ro&rammin& %ecomes a
pro%lem %ecause o redundanc". Since there are t'o 'a"s o doin& the same thin& "ou have to learn
them %oth and that can %e ver" conusin&. . course$ it is at "our discretion to choose the method "ou
are comorta%le 'ith. 3enceorth$ even thou&h there ma" %e man" other 'a"s o doin& a particular
thin&$ 'e 'ill teach "ou onl" one method that 'e ind appropriate.
A varia%le is a 'ord that stores a value. -his value can %e chan&ed at 'ill %" the pro&rammer.
<herever 'e can use a num%er$ 'e can also use a varia%le.
-he ne8t pro&ram ma" seem alien to "ou. -his is %ecause it speaks the truth. ! it inds that a condition
is true it outputs true and i it inds the condition to %e alse it outputs alse. )er" unlike some o "ou$
'ho 'ould do *ust the oppositeF
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine ("{(}") . / *);
System.Console.WriteLine ("{(}") . 0 *);
System.Console.WriteLine ("{(}") * 0 *);
System.Console.WriteLine ("{(}") * 0+ *);
System.Console.WriteLine ("{(}") * 1+ *);
System.Console.WriteLine ("{(}") * 1+,);
}
}
243884333.doc 1E od 221
:utput
6rue
Balse
Balse
6rue
Balse
6rue
Het:s understand this pro&ram line %" line as usual.
3ere the irst line sa"s <riteHine(JQ+RJ$ E U 2)M !s E U 2 ? Ges. So the condition E U 2 evaluates to true.
3ence the Q+R in <riteHine is replaced 'ith -rue and the <riteHine unction displa"s -rue. E U 2 is
called a condition. A condition is like a (uestion 'hich has to result in a "es or no or a true or alse. !n
this case the num%er E is &reater than the num%er 2 and hence the unction evaluates to true. CB
understands the 'ords true and alse.
!n the second <riteHine 'e have the condition E V 2. !s E V 2? /o. So the condition E V 2 evaluates to
alse and hence <riteHine displa"s #alse. Similarl"$ the ne8t condition 2 V 2 is not true and hence
#alse is displa"ed.
!n the ne8t statement 'e have 2 VT 2. 3ere the irst si&n %ein& :V: it is irst checked 'hether 2 V 2? /o$
2 is not less than 2. So then the second si&n :T: is checked i.e.$ 'hether 2 T 2? Ges. So the condition 2
VT 2 evaluates to true and <riteHine displa"s -rue. VT is thus t'o conditions in one .
!n the ne8t <riteHine 'e have the condition 2 FT 2. :FT: means :not e(ual to:. But 2 is e(ual to 2$ hence
the condition evaluates to alse and #alse is displa"ed. -he comparison is alse$ thereore the
condition is alse.
!n the last statement 'e have the condition 2 FT 3. !s 2 FT 3? Ges 2 is not e(ual to 3$ so the condition
evaluates to true and -rue is displa"ed. -his -rue and #alse is a special data t"pe in CB. !t is called
:Bool: or %oolean derived rom Boolean al&e%ra.
a.cs
class zzz
{
static void Main()
{
bool ii;
ii+tr2e;
System.Console.WriteLine ("{(}") ii);
ii+3alse;
System.Console.WriteLine ("{(}") ii);
}
}
:utput
6rue
Balse
!n our previous pro&rams 'e used the data t"pe int or the varia%le ii. -his meant that ii could store
inte&ers or num%ers. Similarl"$ "ou can no' initialiKe ii to either true or alse. -his is possi%le %" usin&
the data t"pe %ool or ii. A data t"pe means the t"pe o data a varia%le can hold. -hereore$ here 'e are
sa"in& %ool ii. !n the irst case 'e are initialiKin& ii to true. So in <riteHine$ Q+R is replaced 'ith true.
!n the second case ii is initialiKed to alse and Q+R is replaced 'ith alse.
!n a &ist$ 'e no' kno' that varia%les can %e either %ool or lo&ical or the" can contain the 'ords -rue
or #alse. Also$ varia%les can also contain num%ers.
243884333.doc 1L od 221
Het:s see ho' CB distin&uishes %et'een data t"pes.
a.cs
class zzz
{
static void Main()
{
bool ii; int 44;
ii+'(;
44+3alse;
}
}
08ecutin& the a%ove pro&ram &ives the ollo'in& errorsA
Compiler 1rror
a.cs(A2"): error C,005&: Constant %alue 7&07 cannot =e con%erted to a 7=ool7
a.cs(72"): error C,009: Cannot implicitl( con%ert t(pe 7=ool7 to 7int7
! "ou 'ant the rain%o'$ "ou &otta put up 'ith some rain. So let7s understand the reason %ehind the
errors. 3ere CB is internall" sa"in& that it distin&uishes %et'een data t"pes. !n that sense CB is ver"
pett" a%out 'hat values "ou &ive to varia%les. Bool can:t mi8 'ith int and vice versa. Since ii is a %ool
"ou can:t initialiKe it to 1+$ 'hich is a num%er. CB is ver" strict a%out this. And %ecause ** is an int "ou
can:t initialiKe it to alse. So "ou have to %e ver" careul a%out ho' "ou initialiKe "our varia%les. Ater
all it doesn:t make sense to ask someone 'ho is &ood at drivin& to teach computers and vice versa.
0ver"one has his or her place in lie. Similarl"$ varia%les also have their place. 3ence a varia%le
declared as a %ool can onl" have values true or alse. Similarl"$ int can have onl" num%ers or inte&ers$
it cannot take true or alse values.
.ur ne8t pro&ram is similar to one o the previous pro&rams.
a.cs
class zzz
{
static void Main()
{
bool ii;
ii+5 0 6;
System.Console.WriteLine ("{(}") ii);
}
}
:utput
6rue
3ere ii is a varia%le o t"pe %ool. !n the ne8t statement 'e have ii T L V P. As "ou alread" kno'$ in
such a case "ou should start %" lookin& to the ri&ht o the :e(ual to si&n:. Because L is less than P the
condition evaluates to true and ii 'ill %e initialiKed to true. 3ence Q+R is replaced 'ith the value o ii$
'hich is true and -rue is displa"ed.
CB is called a stron&l" t"ped lan&ua&e %ecause "ou cannot initialiKe a varia%le o t"pe int to a varia%le
o t"pe %ool. -he reason CB is ver" strict a%out this is %ecause this s"stem eliminates a lar&e num%er
o slopp" pro&rammin& errors. Some lan&ua&es like C on 'hich CB is %ased on do not care 'hat
values "ou initialiKe "our varia%les to. CB is stricter than even 5ava. !n some 'a"s$ it:s like "our
mother 'hen it comes to tellin& "ou 'hat "ou are doin& 'ron& in lie. -hus it is e8tremel" diicult to
243884333.doc 1P od 221
make dum% errors in CB. 1emem%er 'hen "ou are 'ritin& code in CB$ the compiler is al'a"s peerin&
do'n "our shoulder makin& sure "ou do not &et a'a" 'ith an" errors.
I) Statement
So ar the code that 'e have 'ritten is rather useless. -his is %ecause it al'a"s &ets e8ecuted. Hie is
en*o"a%le onl" %ecause it is unpredicta%le. <e don:t kno' 'hat tomorro' is &oin& to %rin&. )ariet" is
the spice o lieF Similarl"$ 'e 'ould like to 'rite computer pro&rams$ 'hich add spice to
pro&rammin&. <e 'ant to 'rite pro&rams that %ehave dierentl" dependin& upon dierent situations
or circumstances. And this can %e achieved 'ith the help o the i statement. So asten "our seat%elts
and &et set to rideF
-he ne8t e' pro&rams 'ill demonstrate the useulness and application o the i statement.
a.cs
class zzz
{
static void Main()
{
i3 ( 3alse )
System.Console.WriteLine ("Hi");
}
}
Compiler 8arnin)
a.cs(A2&): @arnin) C,0&A: Cnreacha=le code detected
!n this pro&ram 'e have included the 'ord :i: ollo'ed %" alse in round %rackets. -his is the i
statement and its s"nta8. S"nta8 is the &rammar in 'ritin&. -hus 'e have no choice %ut to a%ide %" the
rules. !t is called a statement %ecause an"thin& that CB reco&niKes is called a statement. <hen "ou run
this pro&ram$ "ou realiKe that there is no output. So this pro&ram 'ill simpl" displa" nothin&. /o'
"ou kno' 'h" 'e &et the a%ove 'arnin& as our code 'ill never &et e8ecuted.
Het:s understand the rationale %ehind it.
-he i statement lets "ou include decision makin& in "our pro&ram. !t decides 'hether to e8ecute the
ne8t line or not. <hen the i statement evaluates to alse then the ne8t line is i&nored. -he i statement
%rin&s 'ith it the po'er to decide 'hether certain code should %e e8ecuted or not.
-he ollo'in& pro&ram 'ill make this concept clearer.
a.cs
class zzz
{
static void Main()
{
i3 ( 3alse )
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
:utput
<(e
243884333.doc 18 od 221
-he i statement looks at the immediate ne8t line$ it doesn:t look at the line ater that. Since the i
statement inluences onl" one line$ "ou 'ill see onl" B"e displa"ed and not 3i. Same 'arnin& a&ain.
But i "ou 'ant %oth the statements to %e aected %" the i then enclose them 'ithin curl" %races. -his
is illustrated %elo'.
a.cs
class zzz
{
static void Main()
{
i3 ( 3alse )
{
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
}
3ere 'e have included %oth the lines o code 'ithin the %races. /o' the i statement 'ill aect %oth
the lines o code. -he condition %ein& alse$ nothin& is displa"ed. -hus$ the i statement &ives us the
option to e8ecute or not to e8ecute a certain piece o code.
! 'e al'a"s use alse then the code 'ill never %e called. But 'hat did 'e tell "ou a%out conditions?
-he" return either true or alse. So$ in the ne8t pro&ram 'e have 3 U 8 as the condition. Since 3 is not
&reater than 8 the condition evaluates to alse. Since there are no curl" %races$ onl" the ne8t line is
aected %" the i statement. 3ence onl" B"e is displa"ed.
a.cs
class zzz
{
static void Main()
{
i3 ( , / 7 )
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
:utput
<(e
Het:s look at another variation o this pro&ram. /o'$ the interestin& part is that 'herever "ou can use a
condition "ou can also use a varia%le 'hich is o t"pe %ool$ 'hich 'e kno' evaluates to either true or
alse.
a.cs
class zzz
{
static void Main()
{
bool ii;
ii+tr2e;
i3 ( ii )
{
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
243884333.doc 1D od 221
}
:utput
;i
<(e
3ere the varia%le ii is declared as a %ool and then initialiKed to true. !n the ne8t line 'e have i (ii).
-he varia%le ii holds the value true and hence the i condition evaluates to true. -he condition %ein&
true %oth 3i and B"e are displa"ed. /ote that here %oth the statements are included in the curl" %races
resultin& in %oth the statements %ein& aected %" the i statement. -hus the i statement is aectin& a
%lock o statements. >eclaration is another 'a" o sa"in& that 'e are creatin& a varia%le.
!n the ollo'in& pro&ram 'e have an i 'ith the else. ! the i condition evaluates to true then the
statement ollo'in& it is called %ut i it evaluates to alse then the else is called.
a.cs
class zzz
{
static void Main()
{
i3 ( 3alse )
System.Console.WriteLine ("Hi");
else
System.Console.WriteLine ("Bye");
}
}
:utput
<(e
3ere$ since the condition evaluates to alse the else is called and hence B"e is displa"ed. -hus the
additional else statement speciies a statement that is e8ecuted 'hen the condition is alse. -his
construction covers all possi%ilities$ as a condition can %e either true or alse. !n an :i6else: construct
one o them have to %e e8ecuted. Computer pro&rams are said to %e made intelli&ent %ecause o the i
statement. -he more the use o the i statement$ the more intelli&ent "our pro&ram %ecomes. -he i
statement is one o the main %uildin& %locks o an" pro&rammin& lan&ua&e. -hus all pro&rammin&
lan&ua&es have to have a i statement.
Foops
-he i statement is the cornerstone o pro&rammin& %ecause it lends intelli&ence and a decision
makin& po'er to the lan&ua&e. -he second important constituent o an" pro&rammin& lan&ua&e is a
loopin& construct. !n a pro&ram man" times "ou 'ould need to repeat instructions. !n CB$ the or
statement is one orm o a loop that lets "ou repeat statements. 3o'ever$ as 'e alread" kno'$ a
statement can also %e a %lock o statements$ thus it also allo's repetition o multiple statements.
.ur ne8t pro&ram e8plains the or loop.
a.cs
class zzz
{
static void Main()
{
int ii;
3or ( ii + '; ii 0+ .; ii--)
System.Console.WriteLine ("Hi {(}") ii);
}
243884333.doc 2+ od 221
}
:utput
;i &
;i
;i 5
;i "
;i !
-he or has 2 semicolons as part o its s"nta8 or rules. -he statement up to the irst semicolon is
e8ecuted onl" once. #or the irst time and onl" the irst time ii is initialiKed to 1. 1emem%er up to the
irst semicolon the statement is e8ecuted onl" once. -he statement enclosed 'ithin the irst and
second semicolon is a condition. -he condition checks 'hether ii VT E evaluates to true. Since this
condition evaluates to true$ the statement 'ithin the open and the close %races &ets e8ecuted. ! the
condition evaluates to alse$ the statement is i&nored and the loop terminates. -he varia%le ii has a
value 1 'hich is less than E$ so S"stem.Console.<riteHine 'ill %e called 'hich displa"s :3i 1: as the
value o ii is 1. Ater the statement &ets e8ecuted$ the last part o the or i.e. rom the second semicolon
to the closin& %racket &ets e8ecuted. ii,, 'ill increase the value o ii %" 1$ makin& it 2. -he condition
is checked a&ain$ is 2 VT E. -he ans'er here is true$ so :3i 2: is displa"ed. And this roller coaster &oes
on till the condition is alse. <hen ii has the value L$ the condition checked is$ is L VT E. -he ans'er
%ein& alse$ the or terminates. -his is ho' the or statement ena%les the repetition o code.
.ur ne8t e8ample 'ill urther help to illustrate this.
a.cs
class zzz
{
static void Main()
{
int ii;
3or ( ii + '; ii 0+ .; ii--)
System.Console.WriteLine ("Hi {(}") ii);
System.Console.WriteLine ("Hi {(}..") ii);
}
}
:utput
;i &
;i
;i 5
;i "
;i !
;i A..
!n this pro&ram 'e have t'o <riteHine statements. -he or loop ollo's the same rules as the i
statement. -hus in a%sence o curl" %races the or loop 'ill aect onl" the immediate ne8t statement.
-hereore$ the or loop 'ill print num%ers rom 1 to E alon& 'ith hi. -he moment the or loop
terminates$ ii 'ith the dots 'ill print 3i L... -his &oes to prove that 'hen ii has a value si8$ the or loop
'ill terminate.
-he ollo'in& pro&ram demonstrates ho' the or loop ena%les repetition o multiple statements.
a.cs
class zzz
{
static void Main()
{
243884333.doc 21 od 221
int ii;
3or ( ii + '; ii 0+ .; ii--)
{
System.Console.WriteLine ("Hi {(}") ii);
System.Console.WriteLine ("Hi {(}..") ii);
} } }
:utput
;i &
;i &..
;i
;i ..
;i 5
;i 5..
;i "
;i "..
;i !
;i !..
3ere$ %oth the <riteHine statements are enclosed 'ithin curl" %races. -hereore$ %oth the statements
are aected %" the or loop. 3ence$ in this case$ each num%er is displa"ed t'ice alon& 'ith 3i$ once
'ithout the dot and once 'ith the t'o dots.
Similar to the or loop is the 'hile loop.
a.cs
class zzz
{
static void Main()
{
int ii;
ii+';
89ile ( ii 0+ . )
{
System.Console.WriteLine ("Hi {(}") ii);
}
}
}
-he 'hile loop takes a condition$ hence the varia%le ii is initialiKed to 1 %eore enterin& the loop. -he
condition checks 'hether ii VT E evaluates to true. Currentl" the value o ii is 1. -he condition
evaluates to true and the statement 'ithin the curl" %races is e8ecuted. S"stem.Console.<riteHine is
called 'ith 3i and the value o ii. /ote that here 'e are not chan&in& the value o ii 'ithin the loop.
Since the value o ii remains 1 the condition al'a"s evaluates to true and the loop 'ill &o on orever$
indeinitel".
<e can:t have an"thin& &o on orever$ can 'e? -here has to %e a stop to it some'hereF .ur ne8t
pro&ram 'ill resolve this pro%lem.
a.cs
class zzz
{
static void Main()
{
int ii;
ii+';
89ile ( ii 0+ . ){
System.Console.WriteLine ("Hi {(}") ii);
ii--;
243884333.doc 22 od 221
}
}
}
:utput
;i &
;i
;i 5
;i "
;i !
-his pro&ram is similar to the previous one. -he onl" chan&e that 'e have made is that 'e added the
line ii,,M thus or the irst time 3i 1 is displa"ed. -hen the moment ii,, is encountered the value o ii
is incremented %" 1$ makin& it 2. -hen the condition$ 2 VT E$ is checked. -he condition %ein& true$
once a&ain 'e enter the loop and 3i 2 is displa"ed. -his 'ill &o on until ii %ecomes L. .nce ii is L the
condition evaluates to alse and the loop terminates.
Gour mind ma" ponder over the (uestion$ JShould ! use a or or a 'hile?: -he or loop is similar to the
'hile loop. -o ans'er "our (uestion in the most simple manner J.n 9onda"s$ <ednesda"s$ #rida"s
use or and on -uesda"s$ -hursda"s$ Saturda"s use 'hile. Sunda"s 'e assume no one 'rites codeJ.
Alternativel" J-oss a coin$ heads use 'hile$ tails don:t use orJ M6)
!n other 'ords$ it is at "our discretion to use the one "ou are comorta%le 'ith. .nce a&ain CB oers
"ou multiple 'a"s o doin& the same thin&.
3he 4eturn statement
Het:s understand the return statement 'ith our ne8t e8ample.
a.cs
class zzz
{
static void Main()
{
int ii;
ii + abc();
System.Console.WriteLine("9i {(}")ii);
}
static int abc()
{
System.Console.WriteLine("abc");
ret2rn '((;
}
}
:utput
a=c
hi &00
!n this pro&ram$ at irst$ ii is declared as a varia%le o t"pe int. -hen 'e start
e8ecutin& the line iiTa%c()M >oesn:t the ri&ht hand side o the statement rin& a %ell? Aren:t 'e callin&
the unction a%c() ? 3ence at this point the control passes to the unction a%c().
!n the unction 'e have the <riteHine statement$ 'hich prints :a%c:. -hereater$ 'e have a return
statement. !t sa"s return 1++. !n eect$ the unction a%c() is returnin& a value 1++. -hus the statement
ii T a%c()M 'ill no' %e read as iiT1++. /o' that ii has a value 1++$ Q+R in <riteHine is replaced 'ith
1++ and in turn 1++ is displa"ed.
243884333.doc 23 od 221
a.cs
class zzz
{
static void Main()
{
int ii;
ii + abc();
System.Console.WriteLine("9i {(}")ii);
}
static void abc()
{
System.Console.WriteLine("abc");
ret2rn '((;
}
}
Compiler 1rror
a.cs(A2A): error C,009: Cannot implicitl( con%ert t(pe 7%oid7 to 7int7
a.cs(&2&): error C,0&7: ,ince 7999.a=c()7 returns %oid2 a return De(@ord must not =e follo@ed
=( an o=Eect e/pression
08ecutin& the a%ove pro&ram results in errors. 3ere 'e have static void a%c(). <hat static means$ 'e
'ill e8plain a little later. !t is 'ith the intention to ena%le "ou to learn %etter$ so please %ear 'ith us.
-he 'ord void means nothin&. So %" sa"in& void a%c() 'e are sa"in& that the unction a%c() does not
return an" value. #unctions ma"Nma"not return values. 0arlier a%c returned an int. <hen a unction
returns void as in this case$ 'e are sa"in& that a%c cannot return a value. But in the unction code 'e
have 'ritten return 1++. -hereore$ %ecause o this contradiction 'e &et the error. /ote that in the
previous pro&ram 'e did not &et an error. -his 'as %ecause 'e had said static int a%c(). 3ere int
si&niies the return t"pe o the unction. Since the unction returns a num%er 'e used int.
!n our ne8t e8ample 'e have made onl" one addition i.e. 'e have added
S"stem.Console.<riteHine(J#inishJ)M ater the return statement.
a.cs
class zzz
{
static void Main()
{
int ii;
ii + abc();
System.Console.WriteLine("9i {(}")ii);
}
static int abc()
{
System.Console.WriteLine("abc");
ret2rn '((;
System.Console.WriteLine(":inis9");
}
}
Compiler 8arnin)
a.cs(&52&): @arnin) C,0&A: Cnreacha=le code detected
:utput
a=c
hi &00
243884333.doc 24 od 221
.n e8ecutin& this pro&ram$ "ou 'ill ind that the output is the same as the previous pro&ram. -o "our
amaKement "ou do not see the 'ord :#inish: displa"ed. /o$ it is not %ecause CB doesn:t like "ou. -he
reason is that an"thin& ater the return statement is i&nored.
-hus$ "ou ma" have a hundred <riteHine statements ater the return statement %ut the" 'ill all %e
i&nored. Simpl" stated$ no lines ater return statement 'ill &et called. -hat is 'h" the CB compiler$
courteous as it is$ &ives "ou a 'arnin& and not an error.
#ore on data t6pes.......
Gou have alread" learnt a%out t'o data t"pes$ int and %ool. .ur ne8t pro&ram introduces a ne' data
t"pe :strin&:.
a.cs
class zzz
{
static void Main()
{
strin; s;
s+ "9ell";
System.Console.WriteLine(s);
}
}
:utput
hell
!n this pro&ram$ the varia%le s is declared as a strin&. -his implies that s 'ill store mainl" letters o the
alpha%et. -hen s is initialiKed to hell$ 'hich is nothin& %ut a collection o the letters o the alpha%et.
/ote that all strin&s have to %e enclosed 'ithin dou%le inverted commas. S"stem.Console.<riteHine
displa"s the value o the varia%le s$ 'hich is :hell:. 0arlier 'e 'rote a strin& in dou%le inverted
commas directl". 3o'ever$ this time 'e are usin& a varia%le name instead.
/o' 'e kno' the irst parameter to the <riteHine unction is a strin&. <e earlier named our varia%le
ii and no' 'e have called it s. Actuall"$ 'e name our varia%les dependin& upon the time 'e 'rite our
pro&rams. Gou decide "our o'n rules or namin& varia%les. An"thin& "ou enclose in dou%le (uotes is
called a strin&. S"stem.Console.<riteHine is smart enou&h to displa" strin&s$ %ools and int.
Het:s look at another variation o the a%ove pro&ram.
a.cs
class zzz
{
static void Main()
{
strin; s;
s+ "9ell";
System.Console.WriteLine( "{(}") s);
}
}
:utput
hell
243884333.doc 2E od 221
-his pro&ram is e8actl" like the previous one$ the onl" dierence %ein& that 'e have used Q+R instead
o 'ritin& onl" s. 3ere the Q+R is replaced 'ith the value o s$ 'hich is :hell:. -hus$ usin& the Q+R is
preera%le as it understands a lar&e num%er o data t"pes and ho' to displa" their values.
Consolidatin&$ our ne8t e8ample incorporates all the data t"pes that 'e have learnt so ar.
a.cs
class zzz
{
static void Main()
{
strin; s;
int ii;
bool 44;
ii+'(;
44+3alse;
s+"9ell";
System.Console.WriteLine("{(} {'} {*}") ii) 44) s);
}
}
:utput
&0 Balse hell
3ere the varia%le s is declared as a strin&. -hen ii is declared as int and ** is declared as %ool. !n the
ne8t three statements 'e are initialiKin& each o the varia%les. ii is initialiKed to 1+$ ** is initialiKed to
alse and s is initialiKed to hell. /o'$ 'ith the help o a sin&le <riteHine statement 'e are displa"in&
the values o all the varia%les. Q+R is replaced 'ith 1+$ Q1R is replaced 'ith #alse and Q2R is replaced
'ith hell. -his &oes to prove that all the data t"pes can %e displa"ed toðer$ in a sin&le <riteHine
statement. -hus$ CB allo's all the data t"pes to co6e8ist in harmon". /o' onl" i the people o our
countr" could do the sameF
0assing parameters to )unctions
B" no' "ou are amiliar 'ith unctions and ho' unctions are called. -he ne8t pro&ram illustrates
ho' parameters are passed to unctions.
a.cs
class zzz {
static void Main()
{
abc('()3alse)"9ell");
}
static void abc(int i) bool 4) strin; s)
{
System.Console.WriteLine("{(} {'} {*}") i)4)s);
}
}
:utput
&0 Balse hell
<e have a&ain used the S"stem.Console.<riteHine unction to displa" values o varia%les or merel"
displa" te8t onto the screen. -o have it print somethin& on to the screen$ 'e had to &ive it the thin&s
that 'e 'anted printed. -hese thin&s are nothin& %ut parameters. <e don:t pass thin&s to unctionsM 'e
pass parameters to unctions. So ar 'e never created our o'n unctions 'ith parameters.
243884333.doc 2L od 221
!n this pro&ram$ 'e are callin& the a%c unction 'ith three thin&s$ 'ith three parameters. -he irst is a
num%er$ the second is a lo&ical value and the third is a strin&. So$ 'e are passin& the values 1+$ alse
and hell to the unction a%c()M -hese values must %e stored some'here$ %ut 'here? <hen 'e create the
unction a%c 'e have to state the names o three varia%les alon& 'ith their respective data t"pes. -his
is %ecause the values that 'e pass 'ill %e stored in these varia%les. 3ence 'e have the varia%les i$ *
and s. -hese are then displa"ed usin& <riteHine. -hereore$ it 'ill output 1+$ #alse and hell. -his is
ho' parameters are passed to unctions in CB. 1emem%er "ou decide 'hat names to &ive to varia%les.
2arameters passed to unctions are also varia%les.
a.cs
class zzz {
static void Main()
{
abc('()3alse);
}
static void abc(int i) bool 4) strin; s)
{
System.Console.WriteLine("{(} {'} {*}") i)4)s);
}
}
Compiler 1rror
a.cs("2&):error C,&!0&: Fo o%erload for method 7a=c7 taDes 77 ar)uments
.n compilin& this pro&ram "ou 'ill encounter the a%ove error. 3ere 'e are callin& a%c 'ith onl" t'o
parameters$ 1+ and alse. <hereas the unction a%c is actuall" created 'ith three parameters. <e are
passin& an erroneous num%er o parameters$ hence the error. Hesson? .ne must pass the same num%er
o parameters that the unction has %een created to accept. A mismatch %et'een the num%er o
parameters %ein& passed and those %ein& accepted 'ill deinitel" assure "ou o an error. -hus as
%eore$ CB does a lar&e num%er o error checks on "our code. #or$ i it allo'ed the a%ove unction call
to &o ahead$ 'hat 'ould the value o the third parameter s %e?
/o' chan&e the order o the values that are %ein& passed. Gour a%c unction should look like this6
a%c(JhellJ$1+$ alse)M
a.cs
class zzz
{
static void Main()
{
abc("9ell")'()3alse);
}
static void abc(int i) bool 4) strin; s)
{
System.Console.WriteLine("{(} {'} {*}") i)4)s);
}
}
Compiler 1rror
a.cs( !2&): error cs&!0: 6he =est o%erloaded method match for 7999.a=c(int2 =ool2 strin))7 has
some in%alid ar)uments
a.cs( !2! ): error cs&!05: +r)ument 7&7: cannot con%ert from 7strin)7 to 7int7
a.cs(!2&): error cs&!05: +r)ument 77: cannot con%ert from 7int7 to 7=ool7
a.cs(!2&!): error cs&!05: +r)ument 757: cannot con%ert from 7=ool7 to 7strin)7
.n e8ecutin& this pro&ram "ou 'ill %e aced 'ith the a%ove errors. -hese errors have resulted due to a
data t"pe mismatch. !t is some'hat like puttin& a round pole in a s(uare pe&F 3o' is it &oin& to it?
243884333.doc 2P od 221
<hile callin& the unction a%c() the irst parameter that 'e are passin& is the 'ord JhellJ. But the
unction a%c() has %een created to accept the irst parameter as an int. 1emem%er 'e told "ou$ not so
lon& a&o$ that CB distin&uishes %et'een data t"pes. -hus "ou can:t store a strin& in a varia%le o t"pe
int. Similarl"$ the value 1+ cannot %e stored as a %ool and alse cannot %e stored as a strin&. -hereore$
not onl" should the num%er o parameters %ein& passed and accepted %e the same %ut also their data
t"pes must match.
Hike oil and 'ater do not mi8$ in the same 'a" "ou cannot &ive CB an int 'hen it 'ants a strin&. As
said earlier$ some lan&ua&es are more or&ivin& then CB due to 'hich the pro&rammer makes more
mistakes in them.
a.cs
class zzz
{
static void Main()
{
abc();
}
}
class yyy
{
static void abc()
{
System.Console.WriteLine("abc");
}
}
Compilation 1rror
a.cs(!2&): error C,0&05: 6he name 7a=c7 does not e/ist in the class or namespace 79997
Seems like 'e are hooked on to errorsF
!n this pro&ram 'e have created another class called """. <e can have as man" classes in one .cs ile
as 'e like. -his pro&ram no' has t'o classes$ KKK and """. -he class KKK has a unction called 9ain.
9ain denotes the startin& point o our code and as such is the irst unction to %e called. -he class """
contains a unction called a%c. 3ere 'e are callin& the unction a%c %" sa"in& a%c()M in class KKK. But
class KKK does not have an" unction %" the name a%c. 9erel" &ivin& a%c()M encoura&es CB to assume
that a%c() e8ists 'ithin the class KKK. But our a%c unction is contained in """. 3ence 'e &et an error
as 'e are tr"in& to call a unction that e8ists in another class.
But 'e are adamantF <e 'ant to use the a%c unction that """ has. !t:s human tendenc" to 'ant thin&s
that others haveF So$ in the ne8t pro&ram 'e are callin& the unction a%c in the class """ %" 'ritin&
""".a%c()M
a.cs
class zzz
{
static void Main()
{
yyy.abc();
}
}
class yyy
{
static void abc()
{
System.Console.WriteLine("abc");
243884333.doc 28 od 221
}
}
Compilation 1rror
a.cs(!2&): error cs0&: 7(((.a=c() is inaccessi=le due to its protection le%el.
<hen 'e sa" """.a%c()M 'h" the dot? """ is the name o the class and a%c() is the name o the
unction . 0ach o these names can %e as lar&e as "ou 'ant$ so to separate them a dot is used. -hus
'hen "ou 'ant to access a unction that %elon&s to another class "ou can do so %" speci"in& the class
name and unction name separated %" a dot. -he dot is like the semicolon. -he desi&ners o the
lan&ua&e 'anted some character as a separator %et'een class name and unction name$ the" chose the
dot$ the" could have also chosen the semicolon a&ain.
Gou 'ill no' realiKe 'h" 'e sa" Console.<riteHine. .%viousl"$ it means that Console is a class and
'ithin the class Console there is a unction called <riteHine.
But to "our disma"$ on e8ecutin& this pro&ram "ou still &et an error. <ell$ e' people &et 'hat the"
'ant$ ho'ever e'er still 'ant 'hat the" &etF Gou ma" 'ant a particular thin& %ut "ou 'ill not &et it
unless the other part" &ives "ou the permission to take it$ use it or share it. Gour onl" other option is to
put up a i&htF
<e &et an error here %ecause 'e haven:t used the 'ord pu%lic. -he 'hole idea %ehind CB is its
usa%ilit" on the net. And the onl" 'a" "ou can use it on the net is %" havin& securit" precautions. So in
CB the deault rule is 6 "ou can:t use an"thin& unless e8plicitl" &ranted permission. /e8t (uestion.
3o' do "ou &rant the necessar" permission?
Bein& its non6violent sel$ CB &rants permission %" usin& the 'ord pu%lic. <hen 'e sa" pu%lic$ 'e
mean the 'orld at lar&e. So %" startin& 'ith the 'ord pu%lic 'e are sa"in& that the 'hole 'orld is no'
allo'ed to use this unction as 'e are e8plicitl" &rantin& "ou ri&hts. ! "ou don:t use the 'ord pu%lic it
'ill &ive "ou an access error.
-o recti" the error$ add the 'ord pu%lic *ust as 'e have done %elo'.
a.cs
class zzz
{
static void Main()
{
yyy.abc();
}
}
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
:utput
a=c
#inall"$ 'e have the correct codeF See$ one o lie:s &reatest ironies is the act that 'hen "ou inall"
master a tou&h *o%$ "ou make it look eas"FF B" usin& the 'ord pu%lic in ront o the unction a%c$ 'e
can no' call it rom KKK %" speci"in& """.a%c()M /o' that the unction is called$ <riteHine displa"s
:a%c:.
243884333.doc 2D od 221
.ur ne8t e8ample 'ill enhance "our understandin& urther.
a.cs
class zzz
{
static void Main()
{
yyy.abc();
abc();
zzz.abc();
}
2blic static void abc()
{
System.Console.WriteLine("abc in zzz");
}
}
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
:utput
a=c
a=c in 999
a=c in 999
/o' 'e &o a step urther. !n the a%ove pro&ram 'e have t'o a%c unctions$ one in class KKK and one
in class """. ! "ou 'ant to call the one in """ then "ou sa" """.a%c()M %ut i "ou 'ant to call the one
in KKK then "ou sa" KKK.a%c() or a%c(). -he unction a%c()$ %" itsel$ 'ill ask 'hich class is it? Since
a%c() is in KKK itsel$ CB assumes it to KKK.a%c()M B" implication$ i the unction e8ists 'ithin the same
class$ it is optional to preace the unction 'ith the name o the class. <hen "ou e8ecute this pro&ram$
""".a%c() 'ill call the a%c unction in class """ and <riteHine 'ill displa" :a%c:. -hereater$ %oth a%c()
and KKK.a%c() 'ill call the a%c unction in class KKK. And in each case <riteHine 'ill displa" :a%c in
KKK:. -hus i "ou do not preace the unction name 'ith the name o the class$ CB 'ill add the name o
the class in 'hich "ou are callin& the unction. !n our case it is KKK.
2
/amespaces
/ormall"$ students have an implicit trust in their teachers. #or the" kno' that i the %lind lead the
%lind$ %oth shall all into the ditch. 3o'ever$ our philosoph" is that a &ood teacher has to %e an even
%etter liarFF
!n accordance 'ith this %elie$ initiall" 'e told "ou that <riteHine is the name o a unction. -hen 'e
told "ou that the name is not <riteHine$ it is S"stem.Console.<riteHine. But even that:s not true.
/o' comes the moment o truth.
243884333.doc 3+ od 221
Console is actuall" the name o a class. Ges$ trust usF -here is no cr"in& 'ol here. -he class Console
has a unction called <riteHine. 3ence the name no' %ecomes Console.<riteHine. 3o'ever$ that
leaves out the 'ord S"stem. /o' 'hat does S"stem mean?
<ell$ a num%er o unctions like <riteHine are availa%le in CB. Some unctions 'ill let "ou print$
some 'ill ena%le 'ritin& o data to disk and others 'ill let "ou create &raphics. -he pro%lem that 'e
are posed 'ith is 6 ho' does one remem%er 'hich unction satisies 'hat purpose?
Wou!dnAt it ma7e sense i) -e !ogica!!6 grouped simi!ar )unctions together? So$ 9icrosot thou&ht
that all unctions that can 'rite to the screen could %e made part o one class. All unctions that let "ou
'ork 'ith pictures could %e part o another class. But even then$ "ou 'ill have too man" unctions in
one class. So the" thou&ht o havin& a sin&le hi&her lo&ical &roup. Such that all the unctions that have
an"thin& to do 'ith the screen$ i.e. 'hether "ou are dra'in& pictures or 'ritin& te8t$ %e &rouped once
a&ain into a hi&her %od". -hus all classes that deal 'ith interactin& 'ith a data%ase could &o into a
&roup called >ata.
-he second pro%lem that 'e are posed 'ith is that o name clashes. <hat do 'e mean %" that? /o'$
nothin& can stop me rom creatin& m" o'n class called Console and include a unction called
<riteHine in it. But ho' 'ill CB kno' 'hich Console am ! reerrin& to? -he one that 'e created
ourselves$ or the one that 9icrosot has alread" created. !n order to resolve these pro%lems 9icrosot
decided to take classes and put them into namespaces. What is a namespace8 It is simp!6 a -ord.
3hus -e can !ogica!!6 group e'er6thing as per namespaces.
#rom the a%ove e8planation "ou 'ould have %" no' &uessed that S"stem is nothin& %ut a namespace.
-he ollo'in& pro&rams 'ill help make this concept cr"stal clear.
a.cs
class zzz
{
static void Main()
{
yyy.abc();
abc();
zzz.abc();
}
2blic static void abc()
{
System.Console.WriteLine("abc in zzz ");
}
}
namesace vi4ay
{
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
}
Compiler 1rror
a.cs(!2&): error C,0"A: 6he t(pe or namespace name 7(((7 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
!n the a%ove pro&ram$ the onl" chan&e that 'e have made is that 'e have no' included the class """
in a namespace called vi*a". .n doin& so "ou 'ill realiKe that the same pro&ram that 'orked earlier
doesn:t 'ork an"more. -his is %ecause """ is put in a namespace vi*a".
243884333.doc 31 od 221
A namespace is nothing but a -ord -ith an open and c!ose brace. -he entire class is enclosed
'ithin the namespace. ! "ou 'ant to access a unction %elon&in& to class """ rom another class then
the onl" 'a" to do so is %" sa"in& 'i2a6.666.abc>?G 3hus 6ou speci)6 the namespace )irst. then the
name o) the c!ass )o!!o-ed b6 the name o) the )unction. each o) them separated b6 dots. -hus like
;rdu$ 'e read an"thin& rom the ri&ht and not the let. <e start 'ith the name o a unction$ then the
name o the class and 'hatever is let is the namespace.
3ere KKK has not %een &iven a namespace. I) 6ou donAt speci)6 a namespace then b6 de)au!t the
c!ass is inc!uded in a g!oba! namespace. /o' chan&e """.a%c()M to vi*a".""".a%c() and 'atch the
error disappear.
a.cs
class zzz
{
static void Main()
{
vi4ay.yyy.abc();
abc();
zzz.abc();
}
2blic static void abc()
{
System.Console.WriteLine("abc in zzz ");
}
}
namesace vi4ay
{
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
}
:utput
a=c
a=c in 999
a=c in 999
<e %et "our aces are no' %eamin&F Seems like the secret o happiness is not in doin& 'hat one likes
to do %ut in likin& 'hat one has to do. <e had to &et rid o the error 'hich 'e have succeeded in
doin&. -he error has disappearedM the pro&ram e8ecutes as advertised and it &enerates the same output
as it did previousl".
-hus all the classes and unctions created %" )i*a" can %e included in a namespace called vi*a". !
Sonal creates a namespace %" her name then she can include all the unctions and classes created %"
her in the namespace sonal. -hus there 'ill %e no name clashes at all. -hese namespaces that are
created %" us are called user6deined namespaces 'hereas S"stem is a pre6deined namespace. -hus
S"stem is a namespace in 'hich a class called Console 'as created$ 'hich contained a unction called
<riteHine.
3hus the namespace concept a!!o-s us to create !ogica! groups. So all 8ml related classes can %e in
a namespace called 8ml$ 'e% can %e in a 'e% namespace and so on and so orth.
243884333.doc 32 od 221
But the onl" pro%lem no' is that 'hen "ou start 'ritin& code "ou have to speci" the namespace irst$
then the class name ollo'ed %" the unction name. <ell$ ever"thin& is availa%le %ut or a priceF .ur
consolation is that it is a ver" small price to pa".
a.cs
namesace m2<9i
{
class zzz
{
static void Main()
{
vi4ay.yyy.abc();
abc();
zzz.abc();
m2<9i.zzz.abc();
}
2blic static void abc()
{
System.Console.WriteLine("abc in zzz ");
}
}
}
namesace vi4ay
{
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
}
:utput
a=c
a=c in 999
a=c in 999
a=c in 999
!n the a%ove pro&ram$ 'e have t'o classes KKK and """. -he class KKK is included in a namespace
called mukhi and the class """ is included in a namespace called vi*a".
So 'hen 'e sa" a%c()M in 9ain$ 9ain is in KKK$ so "ou are actuall" 'ritin& mukhi.KKK.a%c()M -his is
%ecause CB 'ill automaticall" e8pand it since the unction a%c is availa%le 'ithin the same class.
3ence it is at "our discretion as to ho' "ou 'ant to 'rite it. Gou can sa" a%c()$ KKK.a%c() or
mukhi.KKK.a%c()M inall" the" all e8pand to namespace.classname.unction name. CB adds the name o
the namespace and the name o the class even i "ou do not speciicall" 'rite it. -he concept o
namespaces is not ver" diicult to understand. !t allo's or a hierarchical &roupin& o classes. !t tells
us 'hich classes are lo&icall" &rouped. !t also avoids classes rom havin& the same name.
a.cs
class zzz
{
static void Main()
{
Console.WriteLine("abc in zzz ");
}
}
243884333.doc 33 od 221
Compiler 1rror
a.cs(!2&): error C,0"A: 6he t(pe or namespace name 7Console7 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
I) -e do not enc!ose our c!ass in a namespace. it becomes part and parce! o) the g!oba!
namespace H H. -his namespace does not contain a class called Console. <e had mentioned earlier that
the class Console is contained in the namespace S"stem. <e do not 'ant to preace the Console class
'ith the namespace S"stem each and ever" time. -he onl" reason %ein& that our in&ers 'ill 'ear out
t"pin& the 'ord S"stem over and over a&ain. So C< !ets us use a shorthand b6 means o) -hich -e
a'oid the pain o) ha'ing to 7eep on -riting the name o) a namespace o'er and o'er again.
a.cs
2sin; System;
class zzz
{
static void Main()
{
Console.WriteLine("abc in zzz ");
}
}
:utput
a=c in 999
-he secret here is not in doin& &reat thin&s$ %ut doin& a small thin& in a &reat 'a". <e &et no error
simpl" %" emplo"in& the 'ord usin& 'hich is part o the CB lan&ua&e. All that usin& does is 'henever
it sees onl" the name o a class$ it &oes and adds (in this case) the 'ord S"stem. -hus 'e do not have
to 'rite the 'ord S"stem over and over a&ain. -his 'orks the 'a" shorthand does.
a.cs
2sin; System;
class zzz
{
static void Main()
{
yyy.abc();
}
}
namesace vi4ay
{
class yyy
{
2blic static void abc()
{
Console.WriteLine("abc");
}
}
}
Compiler 1rror
a.cs(A2&): error C,0"A: 6he t(pe or namespace name 7(((7 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
/o' 'e &et an error or """ and not or Console as the """ class %elon&s to the vi*a" namespace and
not the &lo%al namespace. Because o the usin& ke"'ord$ CB adds the namespace S"stem to """
"ieldin& S"stem.""".a%c and realiKes that S"stem does not contain a class called """. 3ence the error.
a.cs
243884333.doc 34 od 221
2sin; System;
2sin; vi4ay;
class zzz {
static void Main()
{
yyy.abc();
}
}
namesace vi4ay
{
class yyy
{
2blic static void abc()
{
Console.WriteLine("abc");
}
}
}
:utput
a=c
-he error vanishes as CB irst tries S"stem.""".a%c &ets an error$ then tries vi*a".""".a%c and is
successul. -hus %" havin& t'o usin&:s 'e do not have to 'rite the namespaces vi*a" or S"stem ever
a&ain.
a.cs
2sin; System;
2sin; m2<9i;
2sin; vi4ay;
namesace m2<9i
{
class zzz
{
static void Main()
{
yyy.abc();
abc();
zzz.abc();
zzz.abc();
}
2blic static void abc()
{
System.Console.WriteLine("abc in zzz ");
}
}
}
namesace vi4ay
{
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
}
:utput
a=c
243884333.doc 3E od 221
a=c in 999
a=c in 999
a=c in 999
<e can have as man" usin&:s as 'e like and the compiler 'ill tr" each one in turn. ! none o them
match 'e 'ill receive an error. !n this case it 'ill tr" 3 times 'ith S"stem$ mukhi and vi*a" and i
none match$ "ou 'ill &et an error.
a.cs
2sin; System.Console;
class zzz
{
static void Main()
{
WriteLine("abc in zzz ");
}
}
Compiler 1rror
a.cs(&27): error C,0&53: + usin) namespace directi%e can onl( =e applied to namespaces4
7,(stem.Console7 is a class not a namespace
Ater the 'ord usin& "ou can onl" 'rite the name o a namespace. S"stem.Console is a namespace
class com%ination 'hich is not allo'ed.
Iui!ding :ierarch6
!n CB "ou or&aniKe classes usin& namespaces. /o' let:s discover the e8tent 'e can &o to as ar as
or&aniKin& classes.
a.cs
class zzz
{
static void Main()
{
m2<9i.vi4ay.yyy.abc();
}
}
namesace m2<9i
{
namesace vi4ay
{
class yyy {
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
}
}
:utput
a=c
!n this pro&ram 'e have a namespace 'ithin a namespace i.e. 'ithin the namespace mukhi 'e have
another namespace vi*a". -hus namespaces are :hierarchical:. ! "ou 'ant to access the unction a%c in
""" "ou have to speci" it in the orm6 namespace.classname.unctionname. So$ the (ualiied name is
no' mukhi.vi*a".""".a%c()M .nce the unction is called$ <riteHine 'ill displa" :a%c:.
243884333.doc 3L od 221
!n order to dierentiate %et'een the various names separated %" dots$ al'a"s read %ack'ards. 1eadin&
%ack'ards$ the irst is the unction name then the class name and the names thereater 'ill all %e
namespaces.
Alternativel"$ "ou can directl" speci" the namespace as mukhi.vi*a"$ as 'e have done %elo'. -his
pro&ram &enerates the same output as previousl"$ it prints a%c.
a.cs
class zzz
{
static void Main()
{
m2<9i.vi4ay.yyy.abc();
}
}
namesace m2<9i.vi4ay
{
class yyy
{
2blic static void abc()
{
System.Console.WriteLine("abc");
}
}
}
:utput
a=c
3ere 'e have a sin&le namespace %" the name mukhi.vi*a". -he name mukhi.vi*a" is actuall" a
shortcut or deinin& a namespace named mukhi that contains a namespace named vi*a". !n this
pro&ram$ 'e have onl" t'o namespaces. But "ou can e8pand it urther to include a num%er o
namespaces dependin& upon the level o hierarch" re(uired %" "our pro&ram.
<e can liken this to an or&aniKation. Het:s consider mukhi to %e the name o the compan". <ithin that
"ou have a su%6compan" or a division called vi*a"$ 'hich creates it o'n classes. As such the level o
hierarch" can %e e8panded.
Beore "ou understand the ne8t pro&ram let:s address a simple (uestion. <h" do "ou use classes?
Classes are used %ecause the" oer a lar&e num%er o unctions. Gou don:t use classes %ecause o the
varia%les that "ou can create 'ithin themM "ou use classes or the unctions that the" provide.
1emem%er$ "ou call a unction usin& the orm 6namespace.classname.unctionname.
%i!e &perations
a.cs
class zzz
{
static void Main()
{
:ile.Coy("c=>>cs9ar>>a.t?t")"c=>>cs9ar>>b.t?t")tr2e);
}
}
Compiler 1rror
a.cs(!2&): error C,0"A: 6he t(pe or namespace name 7Bile7 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
243884333.doc 3P od 221
.ur ne8t pro&ram 'ill enli&hten "ou on somethin& most sou&ht ater 6 -he art o Cop"in&. AhF #inall"
somethin& o interestF
-his pro&ram introduces the :Cop": unction. !t allo's "ou to duplicate a ile. #ile is a class and it has
a unction called Cop"$ 'hich is static.
-he irst parameter :a.t8t: is the source ile i.e. the ile$ 'hich 'e 'ant to duplicate. -he second
parameter :%.t8t: is the destination ile i.e. the ile that 'e 'ant to cop" to. /ote that "ou must speci"
the entire path or the ile name. -he last parameter :true: implies that i the ile e8ists then it 'ill %e
over'ritten. ! the ile does not e8ist it 'ill %e created and contents o the source ile 'ill %e copied
onto it.
And *ust 'hen "ou thou&ht "ou had mastered the art o cop"in& the pro&ram returns 'ith an error
messa&e. -he error sa"s CB does not kno' 'hat #ile.Cop" is. -he pro%lem is that the name o the
namespace is S"stem.!.. So "ou have to speci" the namespace too.
Add the namespace and e8ecute the pro&ram.
a.cs
class zzz
{
static void Main()
{
System."@.:ile.Coy("c=>>cs9ar>>a.t?t")"c=>>cs9ar>>b.t?t")tr2e);
}
}
-he pro&ram does not &enerate an" compilation errors. Create a ile called a.t8t 'ith some te8t %eore
"ou run this pro&ram. 08ecute this pro&ram and then open the ile :%.t8t:. #inall"$ the task has %een
accomplishedF Gou no' have the contents o a.t8t copied into %.t8t.
.ur ne8t pro&ram introduces another unction called :>elete:.
a.cs
class zzz
{
static void Main()
{
System."@.:ile.Aelete("c=>>cs9ar>>a.t?t");
}
}
-he a%ove pro&ram takes the name o a ile as the parameter. -his unction 'ill remove the ile
speciied rom disk. @ive the dir command at the command prompt and "ou 'ill ind that the ile has
%een deleted.
0ver" lan&ua&e 'ill oer "ou millions o such unctions like cop" and delete. -hese unctions
'ere al'a"s availa%le$ %ut CB has &one one step urther and made these unctions a part o a
Class. -he" are no' part o a /amespace. 3ence it %ecomes easier to cate&oriKe unctions. !t
is %ut a (uestion o detail 'hether "ou should or should not cate&oriKe them.
243884333.doc 38 od 221
3
Constructors and >estructors
Ne-
Het:s consider the ollo'in& pro&ram.
a.cs
class zzz
{
static void Main()
{
yyy.abc();
}
}
class yyy
{
2blic void abc() {
System.Console.WriteLine("abc");
}
}
Comiler Brror
a.cs(!2&) : error C,0&0: +n o=Eect reference is reHuired for the nonstatic field2 method or
propert( 7(((.a=c()7
-his pro&ram contains one class called """ 'hich has a unction called a%c. !n 9ain() 'e are usin&
the s"nta8 """.a%c() to call the a%c unction as 'e did earlier. <ithin the a%c unction 'e have the
code or the unction a%c that 'ill print the strin& Ja%cJ. .n compilin& this pro&ram "ou 'ill &et an
error as incomprehensi%le as everF
But ho' is it that 'hen 'e ran this pro&ram earlier 'e didn:t &et an error? ! "ou are still %e'ildered$
'ake up and smell the coeeF >idn:t "ou notice 'e removed the 'ord :static: 'hile sa"in& pu%lic void
a%c(). 3ence 'e &et an error.
!n our earlier pro&rams 'hen 'e 'rote the unction a%c 'e had 'ritten the 'ord static 'hich is
missin& no'.
/o$ 'e are not &oin& to tell "ou to add the 'ord static and e8ecute the pro&ram. <e are not that
predicta%leF .n the contrar"$ 'e shall do somethin& (uite dierent and interestin&. Oeepin& that in
mind let:s consider the ne8t pro&ram.
a.cs
class zzz
{
static void Main()
{
yyy a;
a.abc();
}
}
class yyy
{
243884333.doc 3D od 221
2blic void abc()
{
System.Console.WriteLine("abc");
}
}
Compiler 1rror
a.cs(A2&): error C,0&A!: Cse of unassi)ned local %aria=le 7a7
Beore 'e look into this pro&ram let:s &et our %asics clear. <e have oten used the statement :int i:
meanin& that i 'as a varia%le that looked like an int. <hen 'e used the statement :strin& s:$ it meant
that s 'as a varia%le that looked like strin&. Similarl"$ in this pro&ram 'e are sa"in& """ a. -his
implies that :a: !oo7s !i7e 666. <hat is """? !t is the name o a class. 3ere 'e do not call :a: a varia%le$
'e call it an o%*ect. An o%*ect and a varia%le can %e used interchan&ea%l".
0arlier$ 'henever 'e 'anted to call a mem%er rom a class 'e 'ould sa" """.a%c()M i.e. class name
dot unction name. But in our current pro&ram 'e are sa"in& a.a%c()M <e are usin& the same dot$ %ut
no' it &ives an error sa"in& 6 :;se o unassi&ned local varia%le:. /ote that the 'ord mem%er is
analo&ous 'ith the 'ord unction.
But thin&s still don:t seem an" clearer. So$ let:s &o a step urther and add another statement aTne'
"""()M 9atch "our code 'ith the one %elo'.
a.cs
class zzz
{
static void Main()
{
yyy a;
a+ne8 yyy();
a.abc();
}
}
class yyy
{
2blic void abc()
{
System.Console.WriteLine("abc");
}
}
:utput
a=c
-he 'ord or ke"'ord ne' must %e ollo'ed %" the name o a classM Gou cannot su%stitute it 'ith
an"thin& else$ it must %e a class. !n our case$ 'e have &iven the statement as ne' """(). """ is the
name o an e8istin& class. But 'h" have round %rackets ater the class name? -he :(: and :): %rackets
are part o the s"nta8. And "ou ver" 'ell kno' %" no' that "ou can:t ar&ue 'ith s"nta8.
-hus it is at this point i.e. ater sa"in& ne'$ that the o%*ect :a: that looks like """ is created. <e could
have also called the o%*ect :a: an instance o the class """. Since the class """ has onl" one unction it
'ill allocate memor" or -3A- one unction ./HG. /o' 'e have an o%*ect :a: that looks like class
""". .nce the o%*ect is created$ it can %e used to access the unction rom class """. 3ence$ no' i 'e
sa" a.a%c() 'e 'ill not &et an error.
243884333.doc 4+ od 221
-hus an o%*ect is nothing but an instance or an occurrence o) a c!ass. -hereore$ :a: is an instance o
the class """. -his is ho' "ou can instantiate an o%*ect.
!n order to create an o%*ect "ou must use the ke"'ord :ne':. .ur ne8t pro&ram 'ill help "ou &ain a
%etter understandin& o this concept.
a.cs
class zzz
{
static void Main()
{
int i;
i+ne8 int();
}
}
At irst 'e have int i$ meanin& i looks like int. -hen 'e have iTne' int()M 08ecutin& this pro&ram 'ill
not &enerate an" errors. But so ar 'henever 'e used int i 'e never created the o%*ect i usin& ne'
int(). -his is %ecause CB does this internall" or us. !t saves us the trou%le o doin& so. -hen 'h"
doesn:t CB do so or all the other o%*ects that 'e create? -his is %ecause CB reco&niKes onl" t'o t"pes
o classes.
-he irst t"pe is one that the CB compiler kno's o in advance. int$ lon&$ %ool$ and strin& are classes
that all into this cate&or". -hese are predeined classes. But 'e call them data t"pes %ecause in C and
C,, the" 'ere called data t"pes and CB has a le&ac" o C and C,,. So technicall"$ 'hen 'e sa" int i
it does iTne' int()M internall".
-he second t"pe o classes that CB reco&niKes are the ones that 'e create i.e. user6deined classes. #or
user6deined classes 'e have to create o%*ects ourselves. -hus an"thin& other than the %asic data6t"pes
must %e e8plicitl" created.
So 'hen 'e sa" :""" a: 'e are not creatin& the o%*ect at this point. <e are onl" declarin& the o%*ect to
%e o t"pe """. !t is onl" 'hen 'e use the 'ord :ne': that the o%*ect is created and memor" is
allocated or the same. -hereore$ 'hen 'e have our o'n classes$ that:s the time 'e use ne'. <ithout
ne' "ou cannot create an o%*ect.
Static
Gou are certainl" &oin& to %eneit %" the patience "ou have sho'n so ar. -o ind out ho'$ let:s ollo'
the ne8t pro&ram.
a.cs
class zzz
{
static void Main()
{
yyy a;
a+ne8 yyy();
a.abc();
yyy.!r();
}
}
class yyy
{
2blic void abc()
{
System.Console.WriteLine("abc");
243884333.doc 41 od 221
}
2blic static void !r()
{
System.Console.WriteLine("!r");
}
}
:utput
a=c
pHr
v%.net
Class KKK
Shared Su% 9ain()
>im a As """
aT/e' """()
a.a%c()
""".p(r()
0nd Su%
0nd Class
666666666
Class """
2u%lic Su% a%c()
S"stem.Console.<riteHine(Ja%cJ)
0nd Su%
2u%lic Shared Su% p(r()
S"stem.Console.<riteHine(Jp(rJ)
0nd Su%
0nd Class
!n this pro&ram 'e have t'o unctions a%c and p(r. !t is o si&niicance to note that the unction p(r
has the 'ord static 'hereas a%c does not. ! "ou 'ant to access the static unction p(r "ou sa"
""".p(r() and to access the non static unction a%c "ou sa" a.a%c()M Gou can:t do the reverse i.e. "ou
cant sa" a.p(r() and """.a%c().
a.cs
class zzz
{
static void Main()
{
yyy a;
a+ne8 yyy();
yyy.abc();
a.!r();
}
}
class yyy
{
2blic void abc()
{
System.Console.WriteLine("abc");
}
2blic static void !r()
{
System.Console.WriteLine("!r");
}
}
Compiler 1rror
243884333.doc 42 od 221
a.cs(72&): error C,0&0: +n o=Eect reference is reHuired for the nonstatic field2 method2 or
propert( 7(((.a=c()7
a.cs(32&): error C,0&7A: ,tatic mem=er 7(((.pHr()7 cannot =e accessed @ith an instance
reference4 Hualif( it @ith a t(pe name instead
3he -ord AstaticA imp!ies A)reeA. Static signi)ies that 6ou can access a member or a )unction
-ithout creating an ob2ect. At last "ou are en*o"in& the ruits o patienceF
.%serve that the unction 9ain in KKK is static. -his is %ecause 'e are not creatin& an" o%*ect that
looks like KKK. -he cru8 is that i) 6ou donAt -ant to use Ane-A and 6et use the )unction then 6ou
must ma7e the )unction static.
!n %oth cases a dot is used to reerence the unction. 3he on!6 di))erence is that a static member
be!ongs to the c!ass and as such -e donAt need to create an ob2ect to access it. &n the other hand.
a non,static member. that is the de)au!t. can be accessed on!6 'ia an ob2ect o) the c!ass. 3hus
WriteFine is a static )unction in Conso!e as -e did not create an ob2ect that !oo7s !i7e Conso!e to
access it.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
2blic int i + '(;
}
Compiler 1rror
a.cs(!2A): error C,0&0: +n o=Eect reference is reHuired for the nonstatic field2 method2 or
propert( 7(((.i7
<h" did 'e &et an error? -hink or thinkin& is the hardest 'ork there is$ 'hich is pro%a%l" the reason
'h" so e' en&a&e in it. ! "ou still haven:t &ot it$ let us enli&hten "ou. -he same rules or static appl"
to unctions as 'ell as varia%les. 3ence 'e &et the a%ove error.
a.cs
class zzz
{
static void Main()
{
yyy a + ne8 yyy();
yyy b + ne8 yyy();
a.4 + '';
System.Console.WriteLine(a.4);
System.Console.WriteLine(b.4);
yyy.i + ,(;
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
2blic static int i + '(;
2blic int 4 + '(;
}
243884333.doc 43 od 221
:utput
&&
&0
50
*****************************
)%.net
Class KKK
Shared Su% 9ain()
>im a As """ T /e' """()
>im % As """ T /e' """()
a.* T 11
S"stem.Console.<riteHine(a.*)
S"stem.Console.<riteHine(%.*)
""".i T 3+
S"stem.Console.<riteHine(""".i)
0nd Su%
0nd Class
Class """
2u%lic Shared i As !nte&er T 1+
2u%lic * As !nte&er T 1+
0nd Class
A static varia%le %elon&s to the class. 3ence i 'e create a static varia%le i$ no matter ho' man"
o%*ects 'e create that look like """$ there 'ill %e one and onl" one value o i as there is onl" one
varia%le i created in memor". -hus 'e access a static varia%le %" preacin& 'ith the name o the class
and not name o o%*ect. ! the varia%le is non6static like * then 'e have to use the s"nta8 as e8plained
earlier i.e. name o o%*ect dot name o varia%le. -hus each time 'e create an o%*ect that looks like """
'e are creatin& a ne'Nanother cop" o the varia%le * in memor". <e no' have t'o *:s in memor" one
or a and another or %. -hus * is called an instance varia%le unlike i. <hen 'e chan&e the varia%le * o
a to 11$ the * o % remain at 1+.
-hus unctions are created in memor" onl" once$ irrespective o the 'ord static. ! a class has no
instance or non static varia%les then it makes no sense to create multiple instances o the o%*ect as
there 'ill %e no 'a" o distin&uishin& %et'een the copies created.
Constructors
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("Main");
a+ne8 yyy();
}
}
class yyy
{
2blic yyy()
{
System.Console.WriteLine("yyy");
}
}
243884333.doc 44 od 221
:utput
Main
(((
6666666666666666666666666666
v%.net
Class KKK
2u%lic Shared Su% 9ain()
>im a As """
S"stem.Console.<riteHine(J9ainJ)
aT/e' """()
0nd Su%
0nd Class
Class """
2u%lic Su% /e'()
S"stem.Console.<riteHine(J"""J)
0nd Su%
0nd Class
66666666666666666666666666666666666
!n the a%ove pro&ram 'e have a class called """. <e also have a unction called """ 'hich happens to
%e havin& the same name as the name o the class. <e have a riend named Bunt". Coincidentall"$ the
name o his pet do& is also Bunt"F Similarl"$ it is a%solutel" le&al to have a unction %" the same name
as that o the class. !n this case irst 'e see 9ain and then 'e see """ displa"ed on the screen 'hich
means that the unction """() &ets called automaticall". /ote$ 'e have not called the unction """
e8plicitl".
-his happens to %e a special unction and it is called a :constructor:.
!nitiall" 'e are sa"in& """ a. I6 doing so -e are speci)6ing that AaA !oo7s !i7e 666. We are not
creating an ob2ect that !oo7s !i7e 666. -he ne8t statement has S"stem.Console.<riteHine$ 'hich 'ill
print :9ain:. -hereater$ using ne- -e are creating an ob2ect a. It is at this point that C< ca!!s the
constructor i.e. it calls the unction """(). /o' "ou 'ill see :""": displa"ed. -his &oes to prove that as
soon as an o%*ect o a class is created$ CB automaticall" calls the constructor. A constructor &ets called
at the time o %irth or creation o the o%*ect. It has to ha'e the same name as the name o) the c!ass.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("Main");
a+ne8 yyy();
a.yyy();
}
}
class yyy
{
2blic yyy()
{
System.Console.WriteLine("yyy");
}
}
Compiler 1rror
a.cs(32&): error C,0&&7: 7(((7 does not contain a definition for 7(((7
v%.net
243884333.doc 4E od 221
Class KKK
2u%lic Shared Su% 9ain()
>im a As """
S"stem.Console.<riteHine(J9ainJ)
aT/e' """()
a.666>?
0nd Su%
0nd Class
Class """
2u%lic Su% /e'()
S"stem.Console.<riteHine(J"""J)
0nd Su%
0nd Class
666666666666666666666666666666666
3ere$ 'e are callin& the unction """ usin& the appropriate s"nta8 i.e. %" sa"in& a."""(). /o'$ run the
compiler. Baled %" the error? -he error sa"s :""": does not contain a deinition or :""":. -he class
""" does contain a unction called """ 'hich &ot called in the previous e8ample. 3as CB developed
amnesia all o a sudden? <hat 'ent 'ron&? <ell$ "ou cannot call this unction usin& a."""() or
"""."""() -he catch is that -hen 6ou ha'e a )unction -ith the same name as that o) the c!ass 6ou
cannot ca!! it at a!!. It gets ca!!ed automatica!!6. C< does not gi'e an6one the authorit6 to ca!!
such a )unction. It ca!!s this )unction automatica!!6 on!6 at birth. Seems a%normal doesn:t itF
But 'hat is the purpose o havin& constructors?
A constructor can be used in cases -here e'er6 time an ob2ect gets created and 6ou -ant some
code to be automatica!!6 e1ecuted. 3he code that 6ou -ant e1ecuted must be put in the
constructor. -hat code could %e an"thin&$ it could check or hard disk space$ it could create a ile or it
could connect to the net and %rin& a ile over. <hat that code 'ill do shall var" rom person to person.
-o understand ho' and 'hen the constructor &ets called$ let:s take into consideration our ne8t
e8ample. /o' remove the 'ord :pu%lic: in ront o """() as 'e have done %elo'.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("9i");
a+ne8 yyy();
}
}
class yyy
{
yyy()
{
System.Console.WriteLine("yyy const");
}
}
Compiler 1rror
a.cs(725): error C,0&: 7(((.(((()7 is inaccessi=le due to its protection le%el.
66666666666666666666666666
)%.net
Class KKK
2u%lic Shared Su% 9ain()
243884333.doc 4L od 221
>im a As """
S"stem.Console.<riteHine(JhiJ)
aT/e' """()
0nd Su%
0nd Class
6
Class """
0ri'ate Sub Ne->?
S"stem.Console.<riteHine(J""" constJ)
0nd Su%
0nd Class
.%viousl"$ "ou 'ill &et an error. -his is %ecause 'ithout the 'ord pu%lic the unction is private
propert". And 'hen "ou trespass on private propert" "ou have to ace the conse(uences. !n our case
'e are aced 'ith an error. B" makin& the unction pu%lic ever" one can use it$ it is no' %ecomes
pu%lic propert"F ! the constructor is private then no%od" can create an o%*ect that looks like """.
>o "ou think constructors can return values? Het:s tr" it out and ind out or ourselves.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("9i");
a+ne8 yyy();
}
}
class yyy
{
2blic int yyy()
{
System.Console.WriteLine("yyy const");
}
}
Compiler 1rror
a.cs(&2&): error C,0!": 7(((7: mem=er names cannot =e the same as their enclosin) t(pe
08ecutin& the a%ove pro&ram &enerates an error. !t sa"s that member i.e 666 cannot be the same as
the enc!osing t6pe i.e c!ass 666. /o'$ that is an error that "ou certainl" didn:t e8pect.
Het us anal"Ke 'h" 'e &ot this error.
3ere 'e are sa"in& pu%lic int """ impl"in& that the unction """() is returnin& an int. """() is a
constructor and is called automaticall" at the time an o%*ect is created. ! a constructor is to return a
value then to 'hom should it return the value to? Since it is called automaticall"$ there is nothin& that
can accept the return value. 3hus constructors cannot return 'a!ues. A!so -hen a constructor gets
ca!!ed. an ob2ect is in the act o) being created. It has not 6et been created. 3he 7e6-ord ne- )irst
a!!ocates memor6 )or the )unctions and the 'ariab!es. A)ter this it ca!!s the constructor. When the
constructor )inishes. then -e sa6 that the ob2ect has been created. 3hus the constructor has no
one to return 'a!ues to.
/o' that 'e kno' constructors don:t return values let:s return void instead.
a.cs
243884333.doc 4P od 221
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("9i");
a+ne8 yyy();
}
}
class yyy
{
2blic void yyy()
{
System.Console.WriteLine("yyy const");
}
}
Compiler 1rror
a.cs(&2&5): error C,0!": 7(((7: mem=er names cannot =e the same as their enclosin) t(pe
-hou&h 'e are returnin& void$ 'e &et the same error. -his is %ecause CB is ver" sure o 'hat it sa"s.
<hen "ou %orro' rom other people "ou do so on the prete8t that "ou 'ill return it. !t:s a dierent
stor" that "ou never doF Gou rarel" mean 'hat "ou sa". But 'hen CB sa"s that constructors cannot
return values it means :constructors cannot return values:$ not even :void:. 1emem%er$ there is nothin&
that can accept the return values. 3ence even void cannot %e accepted. When a )unction returns a
'oid -e mean that it -i!! return no 'a!ue at a!!. #or a constructor$ the 'ord return makes no sense at
all.
Constructors -ith parameters
5ust as 'e pass parameters to other unctions$ "ou can also pass parameters to constructors.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("9i");
a+ne8 yyy("no");
}
}
class yyy
{
2blic yyy()
{
System.Console.WriteLine("yyy const");
}
}
Compiler 1rror
a.cs(725): error C,&!0&: Fo o%erload for method 7(((7 taDes 7&7 ar)uments
Gou are alread" a'are o the act that parameters are passed to unctions 'hile callin& them. Similarl"$
'e 'ill pass a parameter to the constructor """ 'hile creatin& the o%*ect aM %ecause it is at this point
that the constructor &ets called.
243884333.doc 48 od 221
3ence 'e are sa"in& aTne' """(JnoJ). But on compilin& this pro&ram "ou &et an error. 3ere$ the
constructor is %ein& called 'ith a strin& :no: as a parameter. But there is no varia%le in the constructor
""" to store the value :no:. Add :strin& s: in the constructor """ and 'atch the error disappear.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
System.Console.WriteLine("9i");
a+ne8 yyy("no");
}
}
class yyy
{
2blic yyy(strin; s)
{
System.Console.WriteLine(s);
}
}
:utput
hi
no
v%.net
Class KKK
2u%lic Shared Su% 9ain()
>im a As """
S"stem.Console.<riteHine(JhiJ)
aT/e' """(JnoJ)
0nd Su%
0nd Class
Class """
2u%lic Su% /e'(B")al s As Strin&)
S"stem.Console.<riteHine(s)
0nd Su%
0nd Class
66666666666666666666666666666666666666
At irst <riteHine 'ill displa" :hi:. -hen 'e have a constructor """ that takes a strin& :no: as a
parameter and accepts it in a varia%le s. -hus the moment the constructor """ is called :no: 'ill %e
displa"ed. -his is %ecause the constructor """ contains code that 'ill print the value stored in the
varia%le s. -his is ho' constructors 'ith parameters are called.
So ar 'e created onl" one instance o the class """. !n the ollo'in& pro&ram 'e are creatin& t'o
instances o the class """$ :a: and :%:.
a.cs
class zzz
{
2blic static void Main()
{
yyy a)b;
System.Console.WriteLine("9i");
a+ne8 yyy("no");
b=new yyy();
}
243884333.doc 4D od 221
}
class yyy
{
2blic yyy(strin; s)
{
System.Console.WriteLine(s);
}
}
Compiler 1rror
a.cs(325): error C,&!0&: Fo o%erload for method 7(((7 taDes 707 ar)uments
<hile creatin& the o%*ect :a: the constructor """ is %ein& passed a parameter :hi:. !n case o the o%*ect
:%: the constructor 'ill %e called 'ithout an" parameters. But in our pro&ram 'e have code onl" or the
constructor 'ith parameters. -r" e8ecutin& this pro&ram and "ou 'ill &et an error sa"in& that method
""" takes + ar&uments. -his is %ecause 'e do not have code or the constructor 'ithout parameters.
Het:s understand the reason %ehind the error.
!n our earlier pro&rams$ 'e did not speci" a constructor. A relevant (uestion here 'ould %e 6 ho' did
the o%*ects &et created then$ 'ithout the constructor %ein& called8 C< is a Good Samaritan. at that
time it inserted a )ree constructor. It does so interna!!6. &n its o-n it inserts a constructor
-ithout an6 parameters. -ithout an6 code into the c!ass.
It !oo7s !i7e this,
yyy()
{
}
2oint to ponder 6 in the a%ove pro&ram$ 'hen 'e didn:t create a constructor 'ithout parameters 'h"
didn:t 'e &et one ree? 1emem%er 'e said CB is a @ood Samaritan? And @ood Samaritans help the
need". .n seein& that 'e alread" have a constructor 'ith parameters$ CB looks the other 'a" i.e.$ it
takes the ree one a'a". 3o'ever. it is on!6 -hen 6ou ha'e no constructor at a!! that C< me!ts its
heart and gi'es 6ou one )ree. 4emember. e'en i) it )inds that 6ou ha'e e'en one constructor it
-i!! ta7e a-a6 the )ree one. .n the assumption that i "ou can provide one constructor$ then 'ith a
little eort "ou can 'ork to'ards providin& the others tooF
/o' the onl" 'a" to &et rid o the error is to add the constructor "oursel.
a.cs
class zzz
{
2blic static void Main()
{
yyy a)b;
System.Console.WriteLine("9i");
a+ne8 yyy("no");
b+ne8 yyy();
}
}
class yyy
{
2blic yyy(strin; s)
243884333.doc E+ od 221
{
System.Console.WriteLine(s);
}
2blic yyy()
{
System.Console.WriteLine("bad");
}
}
:utput
hi
no
=ad
3ere$ initiall"$ the t'o o%*ects :a: and :%: are declared. !n the ne8t statement 'e have <riteHine$ 'hich
'ill displa" :hi:. <e are then creatin& the o%*ect a. At this point the constructor 'ith a strin& as a
parameter is called. !t 'ill no' displa" the value stored in the varia%le s 'hich is :no:. -hereater$ the
o%*ect % is created. At this point the constructor 'ithout the parameters 'ill %e called. -his constructor
contains the <riteHine statement$ 'hich 'ill print :%ad:. 3ere$ 'e have as man" constructors as 'e are
callin& and hence 'e do not &et an" errors.
So$ essentiall". a constructor is a specia! )unction that gets ca!!ed -hen an ob2ect is created. It
does not return an6 'a!ues. not e'en 'oid. As ar as parameters &o it %ehaves like a normal unction.
I) no constructors are speci)ied 6ou get one )ree$ other-ise. 6ou need as man6 constructors as
6ou are ca!!ing. 3ence in the a%ove case 'e cannot create an o%*ect as ne' """(1++) as 'e do not
have a constructor that accepts one int as a parameter.
Destructors
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("Constr2ctor ");
}
~aa()
{
System.Console.WriteLine("Aestr2ctor");
}
}
:utput
Constructor
Iestructor
******************************
)%.net
2u%lic Class KKK
2u%lic Shared Su% 9ain()
>im a As aa T /e' aa()
0nd Su%
243884333.doc E1 od 221
0nd Class
2u%lic Class aa
2u%lic Su% /e'()
S"stem.Console.<riteHine(JConstructor J)
0nd Su%
0ri'ate Su% #inaliKe()
S"stem.Console.<riteHine(J>estructorJ)
0nd Su%
0nd Class
66666666666666666666666
A destructor is a )unction -ith the same name as the name o) a c!ass but starting -ith the
character J. A constructor gets ca!!ed at birth -hereas a destructor gets ca!!ed at death. !n CB
unlike other lan&ua&es 'e do not kno' 'hen an o%*ect dies as unlike 5ames Bond$ 'e do not have a
license to kill. -hus even thou&h the o%*ect a dies at the end o main$ the destructor ma" not &et called.
-hus$ in CB 'e cannot decide 'hen the destructor &ets called. -his decision to call the destructor is
made %" a pro&ram 'ithin CB called the &ar%a&e collector.
-he concept irst &ained currenc" 'ith the advent o 5ava. !n 5ava and CB 'e cannot remove our
o%*ects rom memor". -hus it is or the &ar%a&e collector to decide 'hen to call the destructor. -he
pro&rammin& 'orld 'as replete 'ith errors mainl" %ecause pro&rammers use ne' to allocate memor"
and then or&et to deallocate it. -his &ave rise to a concept called memor" leaks. .n the lip side o the
coin$ pro&rammers deallocated the memor"$ or&ot a%out it and then accessed the o%*ect a&ain. -his
&enerates an error occurrin& at random and diicult to pin do'n.
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("Constr2ctor");
}
public Caa()
{
System.Console.WriteLine("Aestr2ctor");
}
}
Compiler 1rror
a.cs(&"29): error C,0&0A: 6he modifier 7pu=lic7 is not %alid for this item
v%.net
2u%lic Class KKK
2u%lic Shared Su% 9ain()
>im a As aa T /e' aa()
0nd Su%
0nd Class
2u%lic Class aa
2u%lic Su% /e'()
S"stem.Console.<riteHine(JConstructorJ)
0nd Su%
0ub!ic Su% #inaliKe()
243884333.doc E2 od 221
S"stem.Console.<riteHine(J>estructorJ)
0nd Su%
0nd Class
A destructor cannot ha'e an6 modi)iers !i7e pub!ic preceding it.
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("Constr2ctor");
}
Caa(int i)
{
System.Console.WriteLine("Aestr2ctor");
}
}
Compiler 1rror
a.cs(&"2!): error C,&0A: ) e/pected
a.cs(&"2&0): error C,&00: 4 e/pected
a.cs(&A2!): error C,&!&9: >n%alid toDen 7(7 in class2 struct2 or interface mem=er declaration
a.cs(&32&): error C,&0: 6(pe or namespace definition2 or end*of*file e/pected
v%.net
2u%lic Class KKK
2u%lic Shared Su% 9ain()
>im a As aa T /e' aa()
0nd Su%
0nd Class
2u%lic Class aa
2u%lic Su% /e'()
S"stem.Console.<riteHine(JConstructorJ)
0nd Su%
2rivate Su% #inaliKe(I6+a! i As Integer)
S"stem.Console.<riteHine(J>estructorJ)
0nd Su%
0nd Class
Constructors come in p!ent6 -ith di))erent numbers o) arguments being passed to them.
:o-e'er. in the case o) destructors. one siEe )its a!!. i.e.. the6 come in on!6 one siEe. -ith no
parameters. 3ere 'e created a destructor 'ith an int as a parameter there%" conusin& the CB
compiler completel".
CB lacks true s"nchronous or deterministic destructors i.e. destructors %ein& called at a certain point in
time. Gou cannot have "our lie depend on 'hen a destructor 'ould %e called. -he common &rouse
a&ainst CB is that unlike C,, it does not support true destructors.
a.cs
2blic class zzz
{
243884333.doc E3 od 221
2blic static void Main()
{
aa a + ne8 aa();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("Constr2ctor");
}
Caa()
{
System.Console.WriteLine("Aestr2ctor");
}
rotected override void :inalize()
{
}
}
Compiler 1rror
a.cs(&32!): error C,0&&&: Class 7aa7 alread( defines a mem=er called 7Binali9e7 @ith the same
parameter t(pes
******************************
%=.net
-u=lic Class 999
-u=lic ,hared ,u= Main()
Iim a +s aa J Fe@ aa()
1nd ,u=
1nd Class
-u=lic Class aa
-u=lic ,u= Fe@()
,(stem.Console.8rite$ine(KConstructorK)
1nd ,u=
-ri%ate ,u= Binali9e()
,(stem.Console.8rite$ine(KIestructorK)
1nd ,u=
Protected Overrides Sub Finalize()
End Sub
1nd Class
8e tried to create a function called Binali9e. 6he compiler comes =acD and tells us that @e
alread( ha%e a function called Binali9e. 6his is @eird as @e ha%e onl( one Binali9e function.
6he reason for this error is that the compiler con%erts our destructor from Laa to Binali9e.
Arra6s
All pro&rammin& lan&ua&es em%race the concept o arra"s. An arra" is nothin& %ut more o one entit"
i.e.$ a multiple o the same t"pe. Simpl" put$ 'hen 'e have ive %ooks$ 'e don:t *ust sa" 'e have ive
%ooks. !nstead 'e sa" 'e have an arra" o ive %ooks. So$ 'henever "ou 'ant to store multiple values
o varia%les "ou store them in an arra".
a.cs
class zzz
{
2blic static void Main()
{
243884333.doc E4 od 221
intDE a;
a+ ne8 intD,E;
aD(E+ '; aD'E+ '(; aD*E+ *(;
System.Console.WriteLine(aD(E);
aD(E--;
System.Console.WriteLine(aD(E);
int i;
i+';
System.Console.WriteLine(aDiE);
i+*;
System.Console.WriteLine(aDiE);
}
}
:utput
&
&0
0
)%.net
Class KKK
2u%lic Shared Su% 9ain()
>im a() As !nte&er
aT /e' !nte&er(3) QR
a(+)T 1 a(1)T 1+ a(2)T 2+
S"stem.Console.<riteHine(a(+))
a(+) T a(+) , 1
S"stem.Console.<riteHine(a(+))
>im i As !nte&er
iT1
S"stem.Console.<riteHine(a(i))
iT2
S"stem.Console.<riteHine(a(i))
0nd Su%
0nd Class
666666666666666666666666666666666
3ere :a: is an arra" o ints. Gou declare arra"s 'ith a set o WX %rackets. At this point it is not kno'n
ho' lar&e the arra" 'ill %e. #or that 'e have aTne' intW3XM ater ne' 'e have int meanin& 'e 'ant to
create a varia%le o t"pe int. <e are puttin& 3 in the s(uare %rackets meanin& 'e 'ant to store 3 ints.
-his 'ill create three ints aW+X$ aW1X and aW2X. -he" are then initialiKed to the values 1$1+ and 2+
respectivel". -o initialiKe an arra" varia%le 'e use the name$ i.e. in this case a and ollo' it 'ith the
open and close WX %rackets. !nside them 'e put the arra" num%er. -he irst varia%le is called aW+X $ the
second aW1X and so on. CB like most computer pro&rammin& lan&ua&es likes to start countin& rom +
and not 1. -hereore$ the last varia%le is aW2X and not aW3X.
Since an arra" is man" o the same t"pe$ the" all have the same name. !n our earlier e8ample$ even i
'e have man" %ooks$ all the %ooks 'ill %e called %ooks. 3o'ever$ to reer to them individuall" "ou
can sa" %ook1$ %ook2$ %ook3 etc.
<riteHine 'ill displa" the value stored in aW+X 'hich is 1. aW+X,, 'ill increment the value stored in
aW+X %" one. <riteHine 'ill no' displa" 2.
-hereater$ the varia%le i is declared as an int. !t is then initialiKed to 1. <ithin the <riteHine unction
'e have aWiX. !t is not speciicall" stated 'hich varia%le$ instead 'e have said aWiX. -here is no varia%le
called aWiX$ %ut i has a value 1$ so it is read as aW1X. 3ence the value stored at aW1X$ 'hich is 1+$ is
displa"ed. -he ne8t <riteHine 'ill displa" the value stored in aW2X as i is reinitialiKed to 2.
243884333.doc EE od 221
>oin& this makes our pro&ram more &eneric. <e haven:t speciicall" stated 'hich varia%le$ 'e are
lettin& a varia%le called i decide the name o the varia%le.
-he ne8t e8ample demonstrates ho' arra"s can %e used 'ithin loops.
a.cs
class zzz
{
2blic static void Main()
{
intDE a;
a+ ne8 intD,E;
int i;
3or( i+(; i0+*; i--)
aDiE+ iF'(;
3or( i+(; i0+*; i--)
System.Console.WriteLine(aDiE);
}
}
:utput
0
&0
0
-he advanta&e o usin& arra"s is that "ou can decide the name o the varia%le later and the" can also
%e used in loops.
3ere :a: is an arra" o ints and i is a varia%le o t"pe int. -he arra" siKe is 3 i.e. it can store three ints.
-he irst or loop is used to initialiKe the individual arra" items. <ithin the or loop$ i is initialiKed to
+. -he condition iVT2 indicates that the loop 'ill e8ecute thrice. So$ 'hen the control enters the or
loop$ or the irst time i is +. Hookin& at the ri&ht hand side o the e8pression$ iY1+ 'ill no' read as
+Y1+$ 'hich is +. 3ence$ aWiX 'hich is read as aW+X 'ill %e initialiKed to +. i,, increments the value o i
to 1. -he second time aWiX 'ill %e read as aW1X 'hich 'ill %e initialiKed to 1+. -hereater$ aWiX 'ill %e
read as aW2X and initialiKed to 2+ as i is no' 2. /o' i 'ill %e 3$ so the condition evaluates to alse and
the loop terminates.
-he second or loop displa"s the values stored in the arra". -his is similar to the a%ove loop. 3ere 'e
are displa"in& the values o the individual arra" items. As the or loop e8ecutes$ <riteHine 'ill read
aWiX as aW+X$ aW1X and aW2X in each case. As such$ <riteHine displa"s +$1+$2+. So$ startin& rom the
%e&innin& and &oin& upto the end$ all the values stored in the arra" are displa"ed.
Arra"s can also %e used in a oreach statement. -his is e8empliied in the ollo'in& pro&ram.
a.cs
class zzz
{
2blic static void Main()
{
intDE a;
a+ ne8 intD,E;
aD(E+ '; aD'E+ '(; aD*E+ *(;
3oreac9 ( int i in a)
System.Console.WriteLine(i);
}
243884333.doc EL od 221
}
:utput
&
&0
0
-he oreach statement lists the elements o the arra". !t e8ecutes a statement or each element o the
arra" or collection. :a: is an arra" o t"pe int that can store three items. aW+X$ aW1X and aW2X are the
elements or items o the arra". -he" have %een initialiKed to 1$ 1+ and 2+ respectivel". !n the oreach
statement 'e have ( int i in a ).
i is a varia%le o t"pe int and a is the arra" created earlier. -he irst element o the arra" :a: is aW+X and it
holds the value 1. -he oreach statement picks up this value and stores it in i. Since i no' holds the
value 1$ <riteHine displa"s 1. -he second element is aW1X. !t picks up its value$ 'hich is 1+ and stores
it in i. -hus i no' holds the value 1+. <riteHine 'ill no' displa" 1+. -his &oes on or all the elements
o the arra". .ur arra" :a: comprises three elements. 3ence the oreach 'ill e8ecute the <riteHine
statement or each o them and displa" their values 1$1+ and 2+. -he varia%le i is onl" availa%le in the
oreach. -he oreach makes it easier or us to run throu&h all the mem%ers o an" arra".
0arameters 4e'isited -ith &ut and 4e)
+ariab!es are the cornerstone o) programming !anguages. In a -a6. the6 are !i7e items contained
in a bag. =ou can put an item in a bag. remo'e it there)rom. or rep!ace it -ith another. .ur ne8t
e' pro&rams shall %e e8plained alon& these lines.
a.cs
class zzz
{
2blic static void Main()
{
int i+'((;
yyy a;
a+ne8 yyy();
a.abc(i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc(int i)
{
System.Console.WriteLine(i);
i+'(;
}
}
:utput
&00
&00
:a: is an o%*ect that looks """. -he varia%le :i: is initialiKed to a value 1++. -hen the o%*ect :a: that looks
like """ is created. <e are no' callin& the unction a%c 'ith one parameter :i:. <ithin the a%c unction
'e are printin& the value o i. <hen 'e call the unction a%c rom 9ain$ i had a value 1++. So the
243884333.doc EP od 221
varia%le i in a%c also has a value 1++. -hus <riteHine 'ill displa" the value 1++. <e are no'
assi&nin& i a ne' value 1+. But the i that chan&es is the parameter i in a%c$ and not the i o 9ain in
KKK. !t:s like havin& t'o similar %a&s$ 'here "ou chan&e the contents o onl" one. So the <riteHine in
9ain 'ill a&ain print 1++.
3hus the 'ariab!e i -ithin the abc )unction is temporar6. It e1ists on!6 -ithin the ACA and ADA
braces o) the )unction. 3here)ore. this AiA is !oca! to the )unction. Its 'a!ue is not a'ai!ab!e in
#ain. ItAs !i7e 6our memor6. temporar6. !t e8ists as lon& as "ou are readin& this %ook. .nce the
%ook is over ever"thin& is or&ottenF 3hus p!ease do not ca!! the 'ariab!e i in abc as i because it -i!!
con)use e'er6one. 3hus i in abc has nothing to do -ith the i in #ain. rgo. changing i in abc -i!!
ha'e no e))ect on the i in #ain.
Iut a situation cou!d arise -herein 6ou -ou!d !i7e the )unction abc to change the 'a!ue o) i. !n
this conte8t "ou are sa"in&$ ! am &ivin& a varia%le to a unction a%c$ use it$ %ut ! 'ould also like the
unction a%c to chan&e it. And once its value is chan&ed in the unction$ it i.e. the chan&ed value
should %e availa%le in 9ain. Het:s see ho' 'e can handle a situation like that.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i+'((;
a+ne8 yyy();
a.abc(i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc( out int i)
{
i+'(;
}
}
Compiler 1rror
a.cs(32&): error C,&!0: 6he =est o%erloaded method match for 7(((.a=c(out int)7 has some
in%alid ar)uments.
a.cs(327): error C,&!05: +r)ument 7&7:cannot con%ert from 7int7 to 7out int7.
-his pro&ram is e8actl" like the previous one. -he onl" chan&e is that 'e added the 'ord :out: in the
unction a%c alon& 'ith the parameter i. <e &et an error on compilin& this pro&ram. Gou realiKe$ 'e
are sa"in& a.a%c(i) in 9ain$ %ut in the unction 'e are sa"in& a%c(out int i). :out: is the ke" to solvin&
our previous pro%lem. AoutA means -hate'er changes 6ou -i!! ma7e in abc. the6 -i!! be 'isib!e
outside the )unction a!so.
Note that it doesnAt matter -hat 6ou ca!! the 'ariab!e in the )unction abc. the origina! -i!!
change. So. instead o) sa6ing abc>out int i? 6ou cou!d ha'e used another 'ariab!e. In that case. i)
6ou said abc>out int p? it -ou!d be abso!ute!6 !ega!. -o do a'a" 'ith the error "ou must speci" :out:
'hile callin& the unction as 'ell.
/o' 'e have re'ritten the pro&ram 'ith the a%ove chan&e.
a.cs
class zzz
243884333.doc E8 od 221
{
2blic static void Main()
{
yyy a;
int i+'((;
a+ne8 yyy();
a.abc(out i);
System.Console.WriteLine(i);
}
}
class yyy {
2blic void abc( out int i) {
i+'(;
}
}
:utput
&0
6666666666666666666666666
)%.net
Class KKK
2u%lic Shared Su% 9ain()
>im a As """
>im i As !nte&er T 1++
aT/e' """()
a.a%c( i)
S"stem.Console.<riteHine(i)
0nd Su%
0nd Class
Class """
2u%lic Su% a%c(B"1e i As !nte&er)
iT1+
0nd Su%
0nd Class
In this program. -e no- ha'e AoutA in both casesK in the )unction ca!! and the )unction itse!). So
b6 sa6ing a.abc> out i? 6ou are imp!6ing that 6ou are a!!o-ing the )unction abc to change the
'a!ue o) i. -hen in the unction deinition 'e also have the 'ord :out:$ so it kno's i is &oin& to chan&e
and hence i no' chan&es in the ori&inal. -hereore$ <riteHine 'ill displa"s the ne' value 1+.
<e are no' usin& the 'ord :re: instead o :out:. Het us see the eects o doin& so.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i+'((;
a+ne8 yyy();
a.abc(ref i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc( ref int j)
{
4+'(;
243884333.doc ED od 221
}
}
:utput
&0
****************************************************
V=.net
Class 999
-u=lic ,hared ,u= Main()
Iim a +s (((
Iim i +s >nte)er J &00
aJFe@ (((()
a.a=c( i)
,(stem.Console.8rite$ine(i)
1nd ,u=
1nd Class
Class (((
-u=lic ,u= a=c(<(Ref E +s >nte)er)
EJ&0
1nd ,u=
1nd Class
3his program e1ecutes smooth!6 and gi'es the same output as pre'ious!6. !t displa"s the value 1+.
So in that sense :re: is like :out:. !n either case the ori&inal value o :i: chan&es. -hus$ i "ou are callin&
the unction 'ith :re: then state :re: in the unction also. ! "ou are callin& the unction 'ith :out: then
&ive :out: in the unction also.
@ame or some e8perimentation? Het:s tr" to e8ecute the a%ove pro&ram 'ithout initialiKin& the
varia%le i.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i;
a+ne8 yyy();
a.abc(re3 i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc(re3 int 4)
{
4+'(;
}
}
Compiler 1rror
a.cs(32&&): error C,0&A!: Cse of unassi)ned local %aria=le 7i7
3ere 'e are sa"in& int i. /ote that 'e are not initialiKin& i. <e are usin& :re: 'hich &ives us an error.
-he error sa"s :use o possi%l" unassi&ned local varia%le i:. :ere -e didnAt initia!iEe i and 6et -e are
tr6ing to use itG hence -e get an error.
/o'$ let:s look at the ne8t e8ample. 3ere 'e have the same pro&ram onl" no' 'e are usin& :out:
instead o re.
243884333.doc L+ od 221
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i;
a+ne8 yyy();
a.abc(o2t i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc(o2t int 4)
{
4+'(;
}
}
:utput
&0
In this program -e ha'enAt initia!iEed i either but this time -e donAt get an6 error. 3his goes to
sho- that -hen using Are)A the 'ariab!e must be initia!iEed and on!6 then can 6ou change its
'a!ue. !n case o :out: "ou don:t have to initialiKe the varia%le to chan&e its value.
But 'h" have this dierentiation? -his is because in case o) Are)A 6ou can read the 'a!ue o) the
'ariab!e as -e!! as -rite to it. 3here)ore. i) one has to read the 'a!ue o) the 'ariab!e. it must be
initia!iEed be)ore hand. But it is "our discretion 'hether "ou 'ant to chan&e the value$ read it or do
%oth.
Iut in case o) AoutA 6ou can on!6 -rite i.e.. 6ou can on!6 change the 'a!ue o) the 'ariab!e. 6ou
cannot read it. So. in case o) AoutA since it does not read the 'ariab!e it doesnAt matter e'en i) it is
not initia!iEed.
-his is urther e8empliied 'ith the help o the ne8t e' pro&rams. !n the ollo'in& pro&ram 'e have
initialiKed i. /ote here 'e are usin& :out:.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i+'(;
a+ne8 yyy();
a.abc(o2t i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc( o2t int 4)
{
System.Console.rite!ine(j);
4+'(;
243884333.doc L1 od 221
}
}
Compiler 1rror
a.cs(&A2A):error C,0&A!: Cse of unassi)ned local %aria=le 7E7
<ithin the unction a%c 'e are irst printin& the value o i usin& the <riteHine statement. -hat means
'e are tr"in& to read the value o i 'hich is passed to the varia%le * in the unction a%c. But -ith AoutA
one cannot read 'a!ues hence -e get an error. No- i) 6ou tr6 the same program -ith Are)A instead
o) AoutA 6ou -i!! not get an6 errors. 3his is because -ith Are)A 6ou can read the 'a!ues as -e!! as
-e!! as change them.
3o'ever do note that all :out: parameters must %e initialiKed or else "ou 'ill &et an error orm the
compiler as ollo's.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i+'(;
a+ne8 yyy();
a.abc(o2t i);
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc( o2t int 4)
{
}
}
Compiler 1rror
a.cs(&"2&5): error C,0&77: 6he out parameter 7E7 must =e assi)ned to =efore control lea%es the
current method
So 'here can 'e use :out:? We can use AoutA i) -e -ant the )unction to ma7e some ca!cu!ations and
)i!! up the 'ariab!e.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i+'(;
a+ne8 yyy();
a.abc( o2t i );
System.Console.WriteLine(i);
}
}
class yyy
{
2blic void abc( o2t int i )
{
243884333.doc L2 od 221
i= "# $ "#;
}
}
:utput
"00
!n this pro&ram 'e are usin& :out:. <e are multipl"in& 2+ %" 2+ and storin& the result 4++ in i. -here%"
the value o i is chan&ed and <riteHine 'ill no' print 4++.
.ur ne8t e8ample 'ill make thin&s as clear as da"li&ht.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
int i+'(;
int <+*(;
int m;
a+ne8 yyy();
m+a.abc( o2t i) o2t < );
System.Console.WriteLine(i);
System.Console.WriteLine(<);
System.Console.WriteLine(m);
}
}
class yyy
{
2blic int abc( o2t int ?) o2t int y)
{
int 4;
?+,(;y+'(;
4+? F y;
ret2rn 4;
}
}
:utput
50
&0
500
Ater speci"in& that a looks like """$ the t'o varia%les i and k are initialiKed to the values 1+ and 2+
respectivel". -hen the o%*ect a is created. -he third varia%le m is o t"pe int and is used to store the
return value o the unction a%c. B" usin& :out:$ the unction a%c is called 'ith t'o parameters$ i and k.
-he a%c unction has the varia%les 8 and ". <ithin the unction another varia%le * is declared o t"pe
int. -he varia%les 8 and " are assi&ned ne' values 3+ and 1+ respectivel". -heir values are multiplied
and stored in *$ i.e. 3++. -he ne8t statement return * 'ill "ield the value o *$ 'hich is stored in m. /o'
<riteHine 'ill displa" the value o i as 3+. -his is %ecause 'ith the a%c unction 'e illed up i 'ith the
value 3+. Similarl"$ the ne8t <riteHine statement 'ill print the value o k$ 'hich is 1+. -hen 'e print
the value o m$ 'hich is 3++.
!n a nutshell6
!n case o %oth :re: and :out: the ori&inal chan&es.
243884333.doc L3 od 221
A point to note is that 'hen 'e sa" :re: it means 'e 'ill initialiKe the varia%le. -he a%c unction
e8pects the varia%le to %e initialiKed so that the unction can use the value o the varia%le. <hen the
varia%le chan&es the chan&e is relected outside. So$ 'henever "ou sa" :re: the varia%le has to %e
initialiKed$ other'ise an error occurs. -he unction 'ill assume that the varia%le is initialiKed %ecause
it e8pects to read the value. Gou ma" choose to read the value or chan&e it or do %oth.
But 'hen "ou sa" :out: it implies that 'e are not &oin& to initialiKe the varia%le$ that the a%c unction is
not &oin& to use the value$ it is onl" &oin& to chan&e the value. <hen there is an :out:$ a%c can use the
varia%le even i it is not initialiKed. -his is %ecause "ou cannot read the value in case o an :out:
varia%leM the unction can onl" chan&e the value. !n other 'ords$ it has to chan&e the value o the
varia%le to avoid an" errors.
4
Components and >ata%ase
3andlin&
1ception :and!ing
#ailin& to prepare is preparin& to ail. 0r&o$ one is constantl" plannin& and preparin& or the uture. <e
oten set a path or ourselves and tr" to ollo' it steadil". But then lie intervenes. ;ncertainties in lie
result in unoreseen situations. -hese are like e8ceptions in the normal course that 'e set or
ourselves. Similarl"$ 'hen "ou 'rite pro&rams$ unoreseen pro%lems ma" arise durin& its normal path
o e8ecution.
-hese unoreseen pro%lems are nothin& %ut an euphemism or errors. 5ust as in lie$ in the
pro&rammin& 'orld$ these errors can %e urther classiied into %ata! errors and Non,%ata! errors. A
%ata! error is an error that brings the program to a grinding ha!t. A Non,%ata! error is an error
that a!!o-s 6our program to run but -ith !imited capacit6. -his can %e e8empliied %" the
ollo'in&.
Het:s assume "ou have a card that is not o a hi&h resolution. Accordin&l"$ "our %ro'ser displa"s "our
pa&e in a lo'er resolution. /o'$ technicall"$ that is an error %ut it is not a #atal one. 3o'ever$ i "ou
didn:t have a &raphics card at all then it 'ould %e a #atal error. -hus$ 'e ma" also call an unoreseen
pro%lem or error an 08ception. !n other 'ords$ thereore$ the 'ord 08ception is used almost
s"non"mousl" 'ith the 'ord 0rror.
0arlier$ the pro%lem 'as that 'e never centraliKed error handlin&. Het:s assume "ou have to open three
iles. 0ach time "ou open a ile "ou have to check 'hether an error occurred or not. So "ou have to
conduct that check or ever" ile. Since there are three iles$ it 'ould mean repeatin& the same error
check thrice. -hat is surel" a 'aste o time. .r "ou could %e callin& t'o unctions and checkin& or the
same error in %oth the unctions. .ne reason that pro&rammers don:t 'rite error6handlin& routines is
that the" &et tired o the mundane task. !t is the same thin& repeated over and over a&ain.
Het:s consider constructors. Ie)ore the constructor gets ca!!ed. the ob2ect has not 6et been created.
So 6ou as7 the constructor to create an ob2ect. to a!!ocate memor6 and create a )i!e. /o'$ i it
243884333.doc L4 od 221
can:t do so$ ho' 'ill the constructor return to tell "ou that an error occurredF -oda" constructors carr"
a lot o code 'ithin them and i "ou haven:t or&otten$ constructors cannot return values.
Because o the various reasons discussed a%ove$ 'e don:t talk a%out errors an" moreM 'e handle
e8ceptions. Bearin& this in mind let:s understand the ne8t pro&ram.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
a+ne8 yyy();
a.abc();
System.Console.WriteLine("Bye");
}
}
class yyy
{
2blic void abc()
{
t%row new System.&'ception();
System.Console.WriteLine("abc");
}
}
Compiler 8arnin)
a.cs(&A2&): @arnin) C,0&A: Cnreacha=le code detected
:utput
Cnhandled 1/ception: ,(stem.1/ception: 1/ception of t(pe ,(stem.1/ception @as thro@n
at (((.a=c()
at 999.Main()
3ere$ a.a%c calls the unction a%c in class """. S"stem.Console.<riteHine is used to displa" :B"e:. !t is
o si&niicance to note that 'hen "ou run this pro&ram the S"stem.Console.<riteHine does not &et
called. 3ence the 'ord :B"e: is not displa"ed. <ithin the a%c unction 'e have a line that sa"s thro'
ne' S"stem.08ception()M 3he -ord ne- indicates that -e are creating an ob2ect. <e are creatin&
an o%*ect that looks like S"stem.08ception. Athro-A is a reser'ed -ord$ that means it is reco&niKed %"
CB. 08ception is a class in the S"stem namespace. !n other 'ords$ 'e are identi"in& an e8ception$
creatin& an o%*ect o it$ and thro'in& it. -hen 'e have a <riteHine statement or printin& :a%c:. /ote
that neither :B"e: nor :a%c: &ets displa"ed. A 9essa&e Bo8 ma" appear or de%u&&in& the applicaition.
Since 'e are still at the learnin& sta&e$ 'e click on the /o %utton.
3he -arning sa6s that -hen 6ou use the Athro-A 7e6-ord in 6our code. no !ines o) code get ca!!ed
a)ter that. Since the unction a%c is thro'in& an e8ception no code ater the thro' in a%c 'ill &et
e8ecuted. -he thro' acts like the return statement. 0ver"thin& comes to a stand stillF And 'e &et an
error at runtime and not at the time o runnin& the compilerM indicatin& 'here the e8ception occurred.
Also no code &ets called ater unction a%c &ets called as it thro's an e8ception.
08plicitl" declarin& e8ceptions tells the compiler that a particular pro%lem mi&ht occur. <hen the
pro%lem does occur$ an e8ception is thro'nM the ne8t step %ein& to catch the e8ception. Het:s see ho'
'e can accomplish this. !n our pro&ram$ the unction a%c thro's an e8ception. <e 'ill no' catch the
e8ception.
a.cs
class zzz
{
243884333.doc LE od 221
2blic static void Main()
{
yyy a;
a+ne8 yyy();
try
{
a.abc();
System.Console.WriteLine("Bye");
}
catc% (System.&'ception e)
{
System.Console.WriteLine(""n B?cetion"- e.GoStrin;());
}
System.Console.WriteLine("#3ter B?cetion");
}
}
class yyy {
2blic void abc()
{
t9ro8 ne8 System.B?cetion();
System.Console.WriteLine("abc");
}
}
:utput
>n 1/ception,(stem.1/ception: 1/ception of t(pe ,(stem.1/ception @as thro@n.
at (((.a=c()
at 999.Main()
+fter 1/ception
Catching e1ceptions is done -ithin Atr6,catchA b!oc7s. -hereore$ the code or a%c is included 'ithin
a :tr"6catch: %lock. a.a%c 6 the unction that thro's the e8ception 6 is included 'ithin the tr"6catch
%lock . -he a%c )unction thro-s an e1ception b6 using the 7e6-ord thro-. 3here is no other -a6
o) thro-ing an e1ception. At this point all code is skipped in unction a%c as 'ell as the in the tr"
%lock and the control moves to the catch %lock. As such$ neither :a%c: nor :%"e: &ets displa"ed.
Within the catch -e ha'e a parameter AeA that !oo7s !i7e S6stem.1ception. -he o%*ect e has a
method called -oStrin&. -oStrin& is a ver" hand" unction. !t tells "ou 'here e8actl" the e8ception
occurred and in 'hich unction$ unction 'ithin unction. So$ S"stem.Console.<riteline 'ill displa"
the strin& :!n 08ception: alon& 'ith the e8ception.
A)ter the code contained in the catch b!oc7 is e1ecuted. the remaining code a)ter the end o) the
tr6 , catch b!oc7 -i!! be e1ecuted. 3ence$ <riteHine 'ill displa" :Ater 08ception:. -hat means the
pro&ram 'ill not come to a stand still$ it resumes e8ecution ater the catch and not ater the unction
'hich thre' the e8ception. ! "ou &ive a return statement immediatel" ater the catch %lock$ as 'e
have &iven in the ne8t pro&ram$ the pro&ram 'ill stop e8ecution there itsel. 3ence$ in this case$ :Ater
08ception: 'ill not %e displa"ed as sho'n %elo'.
a.cs
class zzz
{
2blic static void Main()
{
yyy a;
a+ne8 yyy();
try
{
a.abc();
System.Console.WriteLine("Bye");
243884333.doc LL od 221
}
catc9 (System.B?cetion e)
{
System.Console.WriteLine(""n B?cetion"- e.GoStrin;());
ret2rn;
}
System.Console.WriteLine("#3ter B?cetion");
}
}
class yyy
{
2blic void abc()
{
t9ro8 ne8 System.B?cetion();
System.Console.WriteLine("abc");
}
}
:utput
>n 1/ception,(stem.1/ception: 1/ception of t(pe ,(stem.1/ception @as thro@n.
at (((.a=c()
at 999.Main()
********************************
%=.nrt
Class 999
-u=lic ,hared ,u= Main()
Iim a +s (((
aJFe@ (((()
6r(
a.a=c()
,(stem.Console.8rite$ine(K<(eK)
Catch e +s ,(stem.1/ception
,(stem.Console.8rite$ine(K>n 1/ceptionKM e.6o,trin)())
Return
1nd 6r(
,(stem.Console.8rite$ine(K+fter 1/ceptionK)
1nd ,u=
1nd Class
Class (((
-u=lic ,u= a=c()
6hro@ Fe@ ,(stem.1/ception()
,(stem.Console.8rite$ine(Ka=cK)
1nd ,u=
1nd Class
0ach time that a%c &ets called an e8ception is thro'n. But "ou ma" not 'ant that to happen. 3ence$
e8ception handlin& is normall" included in an i statement and i an error condition takes place.
A :tr"6catch: %lock can include a num%er o unctions and 'henever an e8ception occurs or an" one o
them$ 'e 'ill catch it. B" doin& so 'e are s"nchroniKin& all the code to handle errors at one place.
Constructors can also thro' e8ceptions.
Iui!ding Components
a.cs
2blic class zzz {
2blic void abc() {
System.Console.WriteLine("zzz abc");
}
}
243884333.doc LP od 221
-he a%ove pro&ram consists o a simple class KKK 'ith one pu%lic unction. -he class has also %een
ta&&ed 'ith the modiier pu%lic that makes it accessi%le to ever"one. <hen 'e run the command csc
a.cs$ 'e are askin& the CB compiler to create an e8ecuta%le ile or us even thou&h 'e did not
e8plicitl" ask it to. An e8ecuta%le ile 'ill al'a"s %e created %" the CB compiler unless "ou override it
%" statin& an option to the CB compiler. Het us start 'ith the Nt option.
csc Nt:li=rar( a.cs
=ou cou!d use Lt or Ltarget. 3his option speci)ies -hat t6pe o) output )i!e the compi!er shou!d
create )or 6ou. I) 6ou do not speci)6 a Lt option on the command !ine. C< b6 de)au!t -rites LtKe1e
)or 6ou thereb6 creating an e1ecutab!e )i!e. -he lon& orm o Nt is Ntar&et and dependin& upon the
time o da"$ choose the appropriate one. /ot all options have a lon& and a short orm like Nt does. 3he
K a)ter the option is mandator6. -hen 'e 'rite the t"pe o e8ecuta%le output ile 'e 'ant. Hi%rar"
means a dll. <hen 'e run the dir command 'e see a ile named a.dll in the current su% director". A
)i!e -ith a .d!! or a .e1e e1tension are ca!!ed Windo-s 0 )i!es. 3his is the de)au!t )i!e )ormat that
Windo-s uses to create e1ecutab!e )i!es. 3here is a minor di))erence bet-een the interna!
structures o) a d!! and a e1e )i!e. Which is that a d!! cannot be e1ecuted !i7e an e1e program can.
B" convention dlls: are used to store code even thou&h an e8e could have also %e used. <hat 'e have
done is created a component.
What i) -e -anted to change the name o) the output )i!e. I6 de)au!t it is the name o) our
program. 3hen -e must use the Lout option as )o!!o-s.
csc /t:library /out:===.dll a.cs
3his -i!! create a )i!e bbb.d!! instead o) a.d!! as ear!ier. <hether 'e use the Nout option or not$ CB
does it or us. ! the CB pro&ram 'as called a.cs$ then CB 'rote NoutAa.e8e on the command line or us.
<e can use the Nout option to chan&e the name o the output ile. Nout does not have a short orm No.
1emem%er CB uses deaults or command line options to make lie easier or us.
/ote that 'e have created a component in a ile %%%.dll
a.cs
class yyy
{
2blic static void Main()
{
zzz a;
}
}
Compiler error
a.cs(!2&): error C,0"A: 6he t(pe or namespace name 79997 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
3he on!6 reason -e create a component is to a!!o- other programs to ca!! code )rom it. !n the
a%ove pro&ram$ 'e are sa"in& that a looks like a class KKK. -he CB compiler is tellin& us in a va&ue
'a" that it does not kno' that KKK is a class. -hou&h 'e kno' KKK is a class as 'e *ust created it and it
is in a ile called %%%.dll$ CB is not a'are o the same.
a.cs
class yyy {
2blic static void Main()
{
zzz a;
243884333.doc L8 od 221
}
}
>csc a.cs /r:bbb.dll
Compiler 8arnin)
a.cs(!2!): @arnin) C,0&A3: 6he %aria=le 7a7 is declared =ut ne%er used
3he Lr or re)erence option te!!s the C< compi!er to !oo7 at bbb.d!!G in this case )or the code o)
c!asses it is not a-are o). !n our case the error disappears as the ile %%%.dll contains the code or the
class %%%.dll. -hus in uture$ i the CB compiler ever &ives "ou the a%ove error$ do not panic. All that
"ou need to do is speci" 'hich dll contains the code or the classes. -he help availa%le alon& 'ith CB$
tells "ou ever" class and the dll that contains the code o the class.
a.cs
class yyy
{
2blic static void Main()
{
zzz a + ne8 zzz();
a.abc();
}
}
:utput
999 a=c
<e have successull" called the unction a%c in class KKK. -he code o the class KKK resides in %%%.dll.
a.cs
namesace m2<9i
{
2blic class zzz
{
2blic void abc()
{
System.Console.WriteLine("zzz abc");
}
}
}
>csc Nt:li=rar( Nout:===.dll a.cs
-he same class KKK is no' enclosed in a namespace mukhi and the component recreated.
a.cs
class yyy
{
2blic static void Main()
{
zzz a + ne8 zzz();
a.abc();
}
}
csc a.cs Nr:===.dll
Compiler 1rror
243884333.doc LD od 221
a.cs(!2&): error C,0"A: 6he t(pe or namespace name 79997 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
a.cs(A2&): error C,0"A: 6he t(pe or namespace name 7a7 could not =e found (are (ou missin)
a usin) directi%e or an assem=l( referenceG)
-he error results as the name o the class is not KKK %ut mukhi.KKK.
a.cs
2sin; m2<9i;
class yyy {
2blic static void Main()
{
zzz a + ne8 zzz();
a.abc();
}
}
:utput
999 a=c
All:s 'ell that ends 'ell.
Databases
Databases are centra!iEed stores o) data. !n a data%ase$ inormation rom several iles (also kno'n
as ta%les) is accessed$ coordinated and operated upon as i in a sin&le ile. -hus$ the data%ase or&aniKes
data independentl" rom the pro&rams that access it. Har&e volumes o data are stored in a data%ase.
Computer pro&rams have little meanin& 'hen 'ritten in isolation. -hereore$ it is o importance to
have our pro&rams 'ork 'ith data%ases. Databases -or7 under the contro! o) a database
management s6stem. SIH Server is an 1>B9SM it is one such data%ase mana&ement s"stem.
Beore 'e can 'rite pro&rams that communicate 'ith data%ases 'e need to have a data%ase. .ne o
the simplest data%ases to use is 9icrosot Access. As a lar&e num%er o people use it$ 'e have %ased
our e8amples on it. 3o'ever "ou could use an" 1>B9S like .racle$ SIH Server as "ou 'ish.
%irst and )oremost. be)ore -e can access a database and per)orm 'arious operations. -e need to
connect to the database. Assumin& "ou 'ant to speak to "our riend over the phone$ "ou dial "our
riend:s phone num%er. !ts onl" 'hen "ou connect to "our riends phone that the %oth o "ou can speak
to each other. Similarl"$ i 'e 'ant to use a data%ase 'e irst have to connect to it and onl" then can
'e speak to it.
a.cs
class zzz
{
2blic static void Main()
{
System.Aata.@leAb.@leAbConnection s;
}}
Compiler @arnin)
a.cs(!25!): @arnin) C,0&A3: 6he %aria=le 7s7 is declared =ut ne%er used
Het:s see ho' 'e can connect to a data%ase.
a.cs
class zzz
{
2blic static void Main()
243884333.doc P+ od 221
{
try
{
System.Aata.@leAb.@leAbConnection s;
s + ne8 System.Aata.@leAb.@leAbConnection();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
hell
<ithin the tr" %lock 'e have an o%*ect s that looks like S"stem.>ata..le>%..le>%Connection. Gou
are alread" a'are that S"stem is a namespace$ %ut 'hat a%out >ata and .le>%? <ell$
S"stem.>ata..le>% is the name o the namespace. <e can liken this to an earlier e8ample 'here 'e
created a namespace mukhi.vi*a". 3ierarch" in a namespace can &o to a%surd len&thsF -he help on CB
states that S"stem.>ata..le>% is the name o a namespace and .le>%Connection is a class 'ithin that
namespace. B" sa"in& s T S"stem.>ata..le>%..le>%Connection()M 'e are creatin& the o%*ect s. <hen
"ou run this pro&ram all that 'e see is the 'ord hell$ 'hich means that the constructor thre' no
08ception. ! it did then the catch %lock 'ould have %een e8ecuted.
a.cs
class zzz
{
2blic static void Main()
{
try
{
System.Aata.@leAb.@leAbConnection s;
s + ne8 System.Aata.@leAb.@leAbConnection();
s.@en();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
,(stem.>n%alid:peration1/ception: 6he Connection,trin) propert( has not =een initiali9ed.
at ,(stem.Iata.:leI=.:leI=Connection.:pen()
at 999.Main()
-he class .le>%Connection has a unction called .pen 'hich opens or connects to our data%ase.
<hen 'e run the a%ove the a%ove pro&ram$ the .pen unction thro's an e8ception. /o'$ at this point
"ou must catch the 08ception. -he -oStrin& 'ithin the catch %lock displa"s the 08ception messa&e.
-he error sa"s that the ConnectionStrin& propert" has not %een initialiKed.
243884333.doc P1 od 221
-he reason an e8ception occurred is that 'e did not provide certain mandator" inormation 'hilst
creatin& the o%*ect. <e did not indicate the location o the data%ase server that 'e 'ant to connect to
or the data%ase. !t:s like pickin& up the phone and not dialin& a num%er. 3o' in the 'orld do "ou
e8pect to connect thenF
<e 'ill no' provide the constructor 'ith some %asic inormation.
a.cs
class zzz
{
2blic static void Main()
{
try
{
System.Aata.@leAb.@leAbConnection s;
s + ne8 System.Aata.@leAb.@leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb;");
s.@en();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
,(stem.Iata.:leI=.:leI=1/ception: Could not find file 7c:\999.md=7. at
,(stem.Iata.:leI=.:leI=Connection.-rocessResults(>nt5 hr)
at ,(stem.Iata.:leI=.:leI=Connection.>nitiali9e-ro%ider()
at ,(stem.Iata.:leI=.:leI=Connection.:pen()
at 999.Main()
We )irst speci)6 the database pro'ider as 0ro'iderM#icroso)t.9et.&FDI.4./. -hich stands )or
#S,Access and then the path as Data SourceMcKNNEEE.mdb separated b6 semico!on.
<hen "ou run the pro&ram$ an .le>%08ception is thro'n$ 'hich sa"s could not ind ile :cAZKKK.md%:.
-his is %ecause 'e have not created an 9SAccess >ataBase called KKK.md%.
An md% ile stores data rom multiple ta%les. !n this ile KKK.md%$ create one ta%le a%c 'ith 2 ields 1
and 2 $ %oth o t"pe te8t. Add t'o records to this data%ase. -he irst record 'ill contain 1$a1 and the
second record 'ill %e 2$a2.
1e run the pro&ram 'hich no' displa"s hell unlike %eore 'here 'e &enerated an 08ception.
:utput
hell
s..pen opens a connection to the data%ase. -he :2rovider: and :>ata Source: &iven in the constructor
identi" the data%ase.
As 'e have &iven the constructor all the mandator" inormation$ s..pen() 'ill open a connection 'ith
the Access data%ase. -he pro&ram e8ecutes smoothl" and once the connection is esta%lished <riteHine
displa"s :hell:.
243884333.doc P2 od 221
/o' that 'e have esta%lished a connection 'ith the data%ase$ let:s see ho' 'e can communicate 'ith
it. 9ore speciicall"$ let:s see ho' 'e can e8ecute an SIH command.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("Create Gable a' ( vno inte;er ) name c9ar('())")s);
c.B?ec2teJon%2ery();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
hell
0mplo"in& usin&$ 'e do not have to preace ever" class 'ith the namespace S"stem.>ata..le>%. -he
purpose o this pro&ram is to e8ecute an SIH statement. SIH is a short orm or Structured Iuer"
Han&ua&e. !t is not a computer pro&rammin& lan&ua&e like CB %ut rather a lan&ua&e like 0n&lish. SIH
understands certain 'ords like Create$ 'hich create a ta%le or us in our data%ase. SIH has nothin& to
do 'ith .racle or Access$ it 'orks 'ith all the 1>B9Ss o the 'orld.
Create Gable a' (vno inte;er) name c9ar('())
-he a%ove SIH statement means that a ta%le called a1 'ill %e created in our data%ase. !t 'ill have 2
ields vno and name. )no 'ill store num%ers and name 'ill store characters su%*ect to a ma8imum o
1+.
A c!ass in an6 programming !anguage is made up o) a co!!ection o) 'ariab!es and )unctions. -hese
put toðer do somethin& or us like solvin& a particular pro%lem or accomplishin& a certain task. <e
live in a 'orld o specialiKation. 5ust like it is diicult to come across one human %ein& 'ho is a 23>
in /uclear Science as 'ell as Sociolo&"$ classes too are 'ritten to ocus on one particular task onl".
-hus 'e need one class to handle our connection to a data%ase and another class 'hich understands
SIH. <e irst create an o%*ect that looks like an .le>%Connection$ 'hich understands ho' to connect
to a data%ase usin& a strin& attri%utes :2rovider: and :>ata Source:$ 'hich it passes as a parameter to the
constructor. -hen 'e create an o%*ect c 'hich looks like .le>%Command as this class understands
SIH. -he constructor &ets called 'ith 2 parameters$ the SIH statement and also the connection o%*ect.
-hus the o%*ect c no' comprises the necessar" inormation re&ardin& the command 'e 'ant to
e8ecute and the connection. /o'$ c.08ecute/onIuer"() 'ill actuall" e8ecute the SIH statement.
08ecute/onIuer"() is a unction 'ithin the .le>%Command class that ena%les us to e8ecute an"
SIH command. Gou 'ill no' see the 'ord :hell: displa"ed on "our screen.
243884333.doc P3 od 221
But did the ta%le &et created? Het:s ind out %" startin& Access and then choosin& the data%ase KKK.
3ere 'e 'ill see the ta%le a1 'ith 2 ields vno and name %ut 'ith no data at all. <e created our ta%le
alri&ht$ %ut it is empt" as it has no data in itF So let:s start insertin& dataNrecords into the ta%le. Beore
doin& so$ Iuit out o Access
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("insert into a' val2es(')K9iK)")s);
c.B?ec2teJon%2ery();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
} }
:utput
hell
-he onl" dierence %et'een this pro&ram and the previous one is that this one uses the !nsert SIH
command. 0arlier$ 'e created a ta%le KKK$ no' 'e are insertin& records in KKK. -o the constructor o
.le>%Command 'e are &ivin& t'o thin&s 6 the insert command Jinsert into a1 values(1$:hi:)J and the
connection. !nsert into and values are part o the SIH s"nta8. A1 is the name o the ta%le in 'hich a
resh record 'ill %e added. Ater values$ 'e 'rite the data separated %" commas. -he irst ield 'ill
contain 1 and the second hi. As the second ield has the data t"pe o character$ it has to %e enclosed in
sin&le (uotes. c.08ecute/onIuer" as usual e8ecutes the SIH command and as no e8ception &ets
thro'n $the 'ord :hell: &ets displa"ed..
Het:s cross check to see i the data has %een inserted into KKK %" runnin& Access. AhaF !t displa"s the
record that "ou *ust inserted in the ollo'in& ormat6
vno name
1 hi
/o' it ollo's that i 'e can insert a record then 'e should %e a%le to remove it too. -he ollo'in&
pro&ram uses the delete command to remove all the records rom the ta%le KKK.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
243884333.doc P4 od 221
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("delete 3rom a'")s);
c.B?ec2teJon%2ery();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e) {
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
hell
/o' c.08ecute/onIuer" 'ill e8ecute the delete command. -his command deletes all the data rom
the ta%le. !n Access 'e 'ill see an empt" ta%le. -his proves that the delete command 'as successulF
Apart rom insertin& and deletin& data another operation that is commonl" perormed is updatin& data.
3o'ever$ "ou must have data in "our ta%le to update it. .ur ta%le is empt" ri&ht no'$ so let:s e8ecute
the insert pro&ram once a&ain. Gou 'ill no' have one record in "our ta%le KKK. Ater insertin& a
record$ chan&e the s(l insert command to an update command. -his is sho'n %elo'.
c+ ne8 @leAbCommand("2date a' set vno+,)name+KbadK 89ere vno+'")s);
3ere$ 'e are &ivin& an update statement and our connection to the o%*ect is :c:. -he update statement
'ill chan&e the vno and name to the values speciied. !t 'ill do so or an" record that has vnoT1. <e
have onl" one record in our ta%le and it meets this criteria. /o'$ &o %ack to Access $ "ou 'ill ind that
the record has %een updated as ollo's6
vno name
3 %ad
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;Aata
So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("delete 3rom a''")s);
c.B?ec2teJon%2ery();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
243884333.doc PE od 221
:utput
,(stem.Iata.:leI=.:leI=1/ception: 6he Microsoft Oet data=ase en)ine cannot find the input
ta=le or Huer( 7a&&7. MaDe sure it e/ists and that its name is spelled correctl(.
at ,(stem.Iata.:leI=.:leI=Command.1/ecuteCommand
6e/t1rror;andlin)(>nt5 hr)
at ,(stem.Iata.:leI=.:leI=Command.1/ecuteCommand
6e/tBor,in)leResult(ta)I<-+R+M, d=-arams2 :=EectP e/ecuteResult)
at ,(stem.Iata.:leI=.:leI=Command.
1/ecuteCommand6e/t(:=EectP e/ecuteResult)
at ,(stem.Iata.:leI=.:leI=Command.
1/ecuteCommand(Command<eha%ior =eha%ior2 :=EectP e/ecuteResult)
at ,(stem.Iata.:leI=.:leI=Command.
1/ecuteReader>nternal(Command<eha%ior =eha%ior2 ,trin) method)
at ,(stem.Iata.:leI=.:leI=Command.1/ecuteFon?uer(()
at 999.Main()
>on:t 'orr"$ 'e have simulated this error on purpose. -he ta%le a11 does not e8ist in our data%ase.
-hus an e8ception &ot thro'n %" 08ecuteCommand-e8t and not 08ecute/onIuer" as seen a%ove.
<hat it means is that 08ecute/onIuer" calls 08ecute 'hich calls 08ecuteCommand 'hich inall"
calls 08ecuteCommand-e8t. Also the 'ord hell does not &et displa"ed %ecause o the e8ception
thro'n.
<e 'ill no' e8ecute a simple select statement.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;Aata
So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
hell
<e have e8ecuted dierent SIH commands throu&h our earlier pro&rams. <e 'ill no' tr" and
e8ecute an SIH select statement. !n order to do so$ 'e have &iven the ollo'in& select statement to the
constructor alon& 'ith the connection6 :Select Y rom a%c:. A%c is a ta%le in the data%ase called KKK .
1emem%er$ c looks like .le>%Command. :Select: is part o the SIH s"nta8 like insert $ update . :rom:
is also a reserved 'ord . :a%c: is the name o the ta%le created earlier in Access and populated %" data
243884333.doc PL od 221
ke"ed in %" us. -he :Y: means all ields in the ta%le. <e could have also replaced the Y 'ith a comma
separatin& list o ield names that 'e 'ere interested in.
As .le>%Connection has an .pen unction$ .le>%Command has a 08ecute1eader unction. -his
unction returns an o%*ect that looks like .le>%>ata1eader.
-he unction 08ecute1eader 'ill create an o%*ect that looks like .le>%>ata1eader and initialiKe r to
it. /o e8ception 'as thro'n$ 'hich meant no errors rom our side.
<hat 'e need to do no' is retrieve data rom the a%c ta%le. -he a%c ta%le ma" have ten ields and
t'ent" records. So 'e use 'hat is called a :dataset:. !n other 'ords$ ho' do 'e access data contained
in multiple ro's and multiple columns throu&h our pro&ram? #or e8ample$ 'hen 'e run the select
statement it &ives us the data in ro's and columns. 3o' can 'e achieve this throu&h our pro&ram? -o
do that 'e no' need a third o%*ect 'hich looks like .le>%>ata1eader.
<e can almost eel "our disma" 6 .h noF Another o%*ectF <ell$ there is a ver" &ood reason 'h" "ou
need to have three dierent o%*ects. #irstl"$ "ou need an o%*ect that understands a connection. -hen
"ou need another o%*ect that understands an SIH statement. -his is %ecause some%od" has to e8ecute
that statement. Gou no' need a third o%*ect that 'ill let "ou readNretrieve data. -hat is 'h" 'e have :r:
an o%*ect that looks like .le>%>ata1eader. -hereater$ 'e have c.08ecute1eader. 0arlier 'e used a
unction call 08ecute/onIuer". -his is %ecause in case o an insert$ update or delete 'e didn:t 'ant
an" data to %e retrieved$ 'e didn:t 'ant an ans'er %ackFF
As a recap$ 'e are usin& r to store the value return %" 08ecute1eader. -hat means r 'ill %e illed up %"
08ecute1eader. .n e8ecutin& this pro&ram onl" :hell: is displa"ed.
/o' that 'e have the illed up r$ let:s see ho' 'e can displa" the data.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine("{(}){'}")r.LetMal2e(())r.LetMal2e('));
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
,(stem.>n%alid:peration1/ception: Fo data e/ists for the ro@Ncolumn.
243884333.doc PP od 221
at ,(stem.Iata.:leI=.:leI=IataReader.IoValueChecD(>nt5 ordinal)
at ,(stem.Iata.:leI=.:leI=IataReader.QetValue(>nt5 ordinal)
at 999.Main()
1un this pro&ram. 08pect the une8pected....an errorF -he error sa"s :/o data e8ists or the ro'Ncolumn:
But didn:t the unction 08ecute ill up r? !t did$ %ut it did not position the record pointer on the irst
record. A record pointer is an abstract concept. 3o start -ith it appears 2ust be)ore the )irst
record. 3he )unction Get+a!ue -i!! return the 'a!ue o) the )ie!ds depending upon -here the
record pointer is. At the start it is 2ust be)ore the )irst record. So r can %e also looked at as an
arra" that contains all the ields. We get an error because -e need to read the data into our arra6
)irst. In order to read data into the )ie!ds -e must gi'e r.4ead. Without r.4ead. the records -i!!
not be read into the arra6. so a!so the record pointer -i!! not be mo'ed )or-ard to the )irst
record.
/o' that 'e kno' the reason 'h" the error occurred let:s recti" it %" doin& the needul. Het:s add
r.1ead() to our pro&ram.
a.cs
usin) ,(stem.Iata.:leI=4
class 999
R
pu=lic static %oid Main()
R
tr(
R
:leI=Connection s4
s J ne@ :leI=Connection(K-ro%iderJMicrosoft.Oet.:$1I<.".04
Iata ,ourceJc:\\999.md=K)4
s.:pen()4
:leI=Command c4
cJne@ :leI=Command(Kselect S from a=cK2s)4
:leI=IataReader r4
r J c.1/ecuteReader()4
,(stem.Console.8rite$ine(r.Read())4
,(stem.Console.8rite$ine(KR0T2R&TK2r.QetValue(0)2r.QetValue(&))4
T
catch(,(stem.1/ception e)
R
,(stem.Console.8rite$ine(e.6o,trin)())4
T
T
T
:utput
6rue
&2a&
/o' that 'e have added r.1ead() the pro&ram e8ecutes as advertised. r.1ead() returns true.
-hereater$ the @et)alue() unction 'hich needs the ield num%er as a parameter retrieves the data
associated 'ith the irst and second column. 1emem%er in CB 'e start countin& rom Kero and hence
Kero as a parameter to @et)alue 'ill retrieve the value o ield one in the ta%le. -he datat"pe o the
irst ield is numeric and o the second character. 3o'ever$ the unction @et)alue does not seem to
care.
4ead returns true i) more data is a'ai!ab!e to read and )a!se i) it is at the !ast record. Also read
positions the record pointer to the ne8t record.
a.cs
243884333.doc P8 od 221
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
89ile (r.&ead())
System.Console.WriteLine("{(}){'}")r.LetMal2e(())r.LetMal2e('));
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
&2a&
2a
(A displa" o onl" the irst t'o ields o all the records in the ta%le. )
But no' 'e 'ant to displa" all the data in the ields. So -e are using 4ead in a !oop.
-hi!e>r.4ead>??. r.4ead>? returns true as !ong as it can read data. 3he -hi!e !oop continues ti!! the
condition is true. <e are usin& our trusted unction <riteHine to displa" the data o the irst and
second ield. -hus the moment r.1ead() cannot read more data it returns alse and the 'hile loop
terminates. /o' all the data in the t'o ields is displa"ed and as such 'e have a lon& list o data
displa"ed. -o veri" urther$ add some more ields and records to a%c.
5ust as 'e mind our manners in dail" lie 'e must do so in pro&rammin& too. !t is a &ood practice to
shut the door 'hen leavin& a room. Similarl"$ in pro&rams 'e must close 'hat ever 'e opened.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
89ile (r.&ead())
System.Console.WriteLine("{(}){'}")r.LetMal2e(())r.LetMal2e('));
r.Close();
243884333.doc PD od 221
s.Close();
System.Console.WriteLine("9ell");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
&2a&
2a
We -i!! mind our manners and gi'e r.C!ose>? and s.C!ose. Note that it is not mandator6 to do so.
%irst -e are c!osing r and then -e are c!osing s i.e. the connection that -e opened.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine(r.:ieldCo2nt);
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--)
System.Console.WriteLine(r.LetJame(i));
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
f&
f
An .le>%>ata1eader has a useul )unction ca!!ed %ie!dCount -hich te!!s 6ou ho- man6 )ie!ds the
SOF statement contained. !n our case a%c has t'o ields. We ha'e one more )unction GetName
-hich -i!! te!! us the name o) the )unction in the tab!e gi'en the )ie!d number. -hus r.@et/ame(1)
'ill &ive us the name o the 2nd ield. !n the or statement$ the varia%le i starts at Kero. -he condition
%ecomes alse 'hen the value o i is one less than r.#ieldCount 'hich in this case is 2 i.e. i 'ill take
values o + and 1. -he reason %ein& i starts rom Kero as @et/ame understands Kero as the irst ield.
-hus 'e can no' print all the column names usin& the or. /o' lets print the entire ta%le irrespective
o the num%er o columns or the num%er o ro's.
243884333.doc 8+ od 221
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
89ile ( r.&ead() )
{
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--)
System.Console.Write(r.LetMal2e(i)-" ");
System.Console.WriteLine();
}
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
& a&
a
Gou can modi" a%c to add more ields and ill in more records. 08ecute the pro&ram and see the
chan&e in output. <henever 'e do not kno' %etter$ 'e use a or or a 'hile i.e. a loopin& construct.
3o'ever 'e do not kno' t'o thin&s. .ne$ the num%ers o ro's in the ta%le and t'o the num%er o
columns. -he irst 'hile takes care o the num%er o ro's and the or$ the varia%le num%er o columns.
-hus the a%ove pro&ram 'ill 'ork or an" num%er o columns and ro's in the ta%le. All that 'e do is
chan&e the select statement. -he dierence %et'een <rite and <riteHine is that <rite does not add an
enter at the end like <riteHine does. Also , is used to *oin t'o strin&s toðer. <e are addin& a space
at the end o ever" ield as a separator.
E
<e% 0na%lin& >ata
<e no' have to our credit$ pro&rams that ena%le e8ecution o a &eneral purpose select statement as
'ell as those that update$ insert and delete commands. -hese 'ere all CB pro&rams 'hich 'ere
compiled into e8ecuta%le iles.
Het:s assume "ou 'ant to displa" the contents o the customer ta%le. .ur pro&ram 'ill ver" 'ell serve
this purpose. Alternativel"$ the pro&ram can %e made to accept user input and dependin& upon the ta%le
243884333.doc 81 od 221
name that the user t"ped in$ the pro&ram can displa" contents o that ta%le. Gou can easil" do so 'ith
the help o a unction called @etHine in Console. @etHine 'ill cause the pro&ram to 'ait at the console
or the user input ollo'ed %" the :0nter: ke".
-his situation comes 'ith its share o pro%lems thou&h. -he pro%lem is that i there are ive people
'ho are &oin& to use this pro&ram then "ou need to &ive them ive copies o the pro&ram. ! there are
ive thousand such users then "ou have to cop" this on to ive thousand dierent machines. Simpl" not
possi%le. <ait a minuteF >id "ou &et a sudden %rain'ave? -he perect solution 'ould %e to :put it on a
net'ork:FF But don:t or&et that there are man" net'orkin& standards availa%le. Some ma" have
/ovell$ some ma" have <indo's 2+++$ and others ma" have the 9acintosh or even Hinu8N;ni8. So
'hat do 'e do no'? Gou 'ill have to make sure that the same pro&ram 'orks under Hinu8 as 'ell as
it does under a 9ac or an" other standard. Apart rom this "ou 'ould have the headache o havin& to
train people to use the pro&ram.
-he onl" solution to this pro%lem is <e% ena%lin& data. -his is the ne' standard o 'ritin& code. Gou
need to access "our data usin& !nternet -echnolo&ies. !t:s onl" then that 'e can eliminate the loopholes
that e8ist 'ithin the alread" availa%le standards.
/o matter 'hich operatin& s"stem "ou install$ alon& 'ith it "ou &et access to a %ro'ser. <hen "ou use
the !nternet "ou use a %ro'ser$ a.k.a. an user a&ent$ that ena%les "ou to vie' 'e% pa&es and ena%les
data transer over the !nternet.
Since 'e do have a %ro'ser$ can:t 'e do a simple thin&? Het the user t"pe the name o our machine
and &et a orm. <ithin the orm he can ke" in the ta%le name and once he does that he 'ill &et the
details o that ta%le. <hich means "ou 'ill no' have to e8ecute "our code on a pro&ram called the
<e%Server. -his is 'hat is meant %" <e% 0na%lin& >ata.
But %eore 'e leapro& into the 'orld o <e% 0na%lin& >ata$ let:s ac(uaint ourselves 'ith the %asic
lan&ua&e that the %ro'ser understands. !t is called 3-9H.
:3#F
Amon&st %ro'sers$ the usual suspects are /etscape /avi&ator and !nternet 08plorer. What happens
-hen 6ou 'ie- a -eb page using such a bro-ser8 3echnica!!6 spea7ing. 6ou connect to a -eb
ser'er and a )i!e comes o'er onto 6our computer. -hich is genera!!6 an :3#F )i!e.
:3#F is the acron6m )or :6per 3e1t #ar7up Fanguage. It is a document,)ormatting !anguage.
:3#F is basica!!6 a stream o) characters -ithout an6 inte!!igent )unctiona!ities !i7e the )or and
i) statements. :ence it cannot be considered an eBui'a!ent o) a programming !anguage. 3-9H$
as simple as it is$ allo's an" %umpkin to %e an ace at itF
Assumin& "ou have a <e% Bro'ser$ let:s 'rite our irst 3-9H pro&ram. Gou can use an" editor like
'ord to t"pe "our pro&ram in. -he onl" thin& that "ou must %ear in mind is that the )i!e must be
sa'ed -ith the e1tension .htm or .htm!. Create the ile in "our root director". !n our case$ 'e 'ill
save in cA and since 'e are usin& the dos editor 'e shall %e&in %" sa"in& edit a.html
C:>edit a.html
-"pe the code as 'e have done %elo'.
a.9tml
Hi
Bye
:utput
243884333.doc 82 od 221
;i <(e
/ote that the te8t must %e on t'o separate lines. .nce "ou have saved "our ile run "our %ro'ser. !n
the %ro'ser "ou 'ill see a 'hite te8t %o8 kno'n as the address %ar. Click there and t"pe cANa.html$ in
our case 'e have saved the ile in the root o the C drive.
As o no' 'e are pickin& up this html ile rom our hard disk. But 'hen "ou are on the /et "ou are
accessin& a ile rom some other machine on the net. !n that case$ "ou &ive the address o that
machine. #or instance$ i "ou 'ant to connect to the 9icrosot site$ "ou 'ill t"pe '''.microsot.com.
Apart rom that there is no dierence in tr"in& this on the /et or o the /et.
When the bro-ser sees an htm! )i!e. it reads it !ine b6 !ine. 3ence$ in the %ro'ser 'indo' "ou 'ill
see 3i B"e displa"ed. <o'F Gou have *ust 'ritten "our irst html pro&ramF
But didn:t 'e 'rite 3i and B"e on t'o separate lines? 3he bro-ser. dumb as it is doesnAt seem to
understand this. Foo7s !i7e the bro-ser. b6 de)au!t. ignores entersF So$ ho' can 'e make the
%ro'ser understand? <e can do so 'ith the help o :ta&s:.
:3#F is based on AtagsA. -hich instruct the bro-ser ho- to disp!a6 a piece o) te1t or an
imageLpicture. A tag begins -ith APA and ends -ith AQA.
So let:s add a ta&.
a.9tml
Hi 0br/
Bye
:utput
;i
<(e
Going b6 the de)inition o) a tag 6ou -i!! rea!iEe that br is a tag. It is enc!osed -ithin the angu!ar
brac7ets. PbrQ means ne1t !ine. Save the ile. /o' 'hen "ou vie' this ile in the %ro'ser "ou 'ill
ind that 3i and B"e are displa"ed on t'o separate lines.
3ence$ :3#F is nothing but a co!!ection o) tags. Gou *ust need to kno' 'hich ta& satisies 'hat
purpose.
a.9tml
0b/ Hi 0Nb/ 0br/
Bye
:utput
Hi
<(e
!n this pro&ram. the tag b means bo!d. Iut here -e a!so ha'e PLbQ. -hich is a c!osing tag. 3his
indicates that -e are c!osing the PbQ tag. <hatever is enclosed %et'een the t'o 'ill %e made %old.
3ence onl" 3i 'ill %e %old. :3#F tags are romantic. most o) them a!-a6s tra'e! in pairs , ca!!ed
an opening tag and a c!osing tag. But some tags like <br> like to play the field for they prefer to
remain single.
5sing the PiQ tag -e -i!! disp!a6 :i in ita!ics.
a.9tml
0i/ Hi 0Ni/ 0br/
Bye
243884333.doc 83 od 221
:utput
Hi
<(e
!t is all ver" mechanicalF ViU means italics and hence 3i is displa"ed in italics. 3ad "ou included %"e
'ithin ViU and VNiU then %"e 'ould %e in italics tooF -hat:s all the understandin& that is re(uired to
learn 3-9HF
/o' 'e have included another ta& Vh1U
a.9tml
0i/ Hi 0Ni/ 0br/
0b/ Bye 0Nb/ 0br/
(%)* Oo2 are Welcome a;ain1 (%)*
:utput
Hi
Bye
You are Welcoe a!ain"
Since 3i is included in ViU VNiU it 'ill %e displa"ed in italics. B"e is displa"ed in %old due to the V%U
ta&. PhiQ means heading1. it ma7es the te1t bigger. -hus$ :Gou are <elcome a&ainF: is displa"ed in a
%i&&er ont.
a.9tml
(%tml*
(body*
0i/ Hi 0Ni/ 0br/
0b/ Bye 0Nb/ 0br/
09'/ Oo2 are Welcome a;ain1 09'/
(+body*
(+%tml*
:utput
Hi
Bye
You are Welcoe a!ain"
-his pro&ram outputs the same result as the a%ove. -he onl" dierence is that no' it is a -e!!,)ormed
:3#F program. 'er6 :3#F )i!e must begin -ith the Phtm!Q and end -ith PLhtm!Q tag.
Whate'er te1t is to be disp!a6ed -ithin the bro-ser must be enc!osed -ithin the Pbod6Q and
PLbod6Q tag. -his is the 'a" an 3-9H pro&ram must %e 'ritten. 3ope the purists have or&iven us
no'F
Het:s make our pa&e attractive %" addin& a picture to it. Cop" an" &i ile to "our root director" and
name it aa.&i. !n our case$ 'e copied it to cA
a.9tml
09tml/
0body/
0i/ Hi 0Ni/ 0br/
0b/ Bye 0Nb/ 0br/
(im, src=-aa.,if-*
243884333.doc 84 od 221
09'/ Oo2 are Welcome a;ain1 09'/
0Nbody/
0N9tml/
img is the image tag. it is used to disp!a6 pictures. Alon& 'ith this ta& "ou have to speci" the name
o the ima&e ile. #ollo'in& the 'ord :im&: is the 'ord :src: and ater the :T: si&n "ou speci" "our
ilename. i.e. aa.&i. Gou can &ive the name o an" picture ile. But ollo' this s"nta8F Another thin& to
note is that 6ou can ha'e the )i!e name inc!uded in sing!e Buotes or doub!e Buotes or 6ou ma6
e1c!ude them tota!!6. -hus vie'in& this ile in the %ro'ser 'ill no' displa" the ima&e "ou speciied
alon& 'ith the te8t. !n 3-9H parlance$ src is called an attri%ute. An attri%ute descri%es N (ualiies a
ta&.
0a 9re3+a.9tml/ Hi 0Na/
0a 9re3+b.9tml/ Bye 0Na/
Gou 'ill see t'o h"perlinks in "our %ro'ser 'indo'. -he names o the html iles 'ill not %e
displa"ed %ut the 'ords 3i and B"e 'ill %e underlined. And i "ou click on hi and %"e the respective
html iles 'ill %e displa"ed instead.
-hen there are ta%les in 3-9H
a.9tml
09tml/
0table border+'(/
0tr/
0td/9i0Ntd/0td/'((0Ntd/
0Ntr/
0tr/
0td/'(((0Ntd/0td/bye0Ntd/
0Ntr/
0Ntable/
0N9tml/
-he ta%le ta& has one attri%ute$ %order$ that speciies ho' the lines or %orders %et'een columns looks
like. -he ta%le ta& encompasses t'o ta&s . tr stands or a ta%le ro' and td or a ta%le columns. <e have
t'o tr:s $ hence 'e have t'o ro's and each tr encloses t'o td:s one or each column.
Similarl"$ "ou can keep addin& more and more ta&s dependin& on ho' "ou 'ant "our pa&e to %e
displa"ed. An" %ook on 3-9H 'ill list all the availa%le ta&s. .ur aim is not to learn html here %ut to
use CB on the /et. Since kno'in& this much 'ill suice our orthcomin& needs$ let:s &et %ack on
trackF
5sing C< on the Net
/o' that "ou are amiliar 'ith the rudimentar" elements o 3-9H$ let:s see ho' 'e can appl" our
recentl" ac(uired kno'led&e in con*unction 'ith CB on the /et.
%irst and )oremost 6ou need a Web Ser'er. 3ence "ou 'ill no' need to install Apache. Gou can
do'nload Apache rom httpANN'''.apache.or& and then run the installer pro&ram. Amon& the Apache
directories$ there are t'o su%6directories that are o importance to us$ namel"$ c&i6%in and htdocs.
-he c&i6%in su%6director" is used or storin& e8ecuta%le iles.
!n order to chan&e to the c&i6%in su%6director" ollo' the path as &iven %elo'.
C:\pro)raL&\apacheL&\apache\c)i*=in
243884333.doc 8E od 221
And to chan&e to the htdocs su%6director" &ive the ollo'in& path.
C:\pro)raL&\apacheL&\apache\htdocs
-he htdocs su%6director" is used or storin& html iles.
-o install the Apache <e% Server all that "ou need to do is do'nload the install pro&ram on "our hard
disk. 1un the e8ecuta%le pro&ram 'hich 'ill install apache in the apache &roup director" o pro&ram
iles. Chan&e to CAZpro&ra[1Zapache[1Zapache director" and then run the 'e% server as ollo's.
C:\pro)raL&\apacheL&\apache >apache
! "ou &et an error a%out some server name$ cd to the con su% director" $ edit a ile called httpd.con $
chan&e a line startin& 'ith BServer/ame to Server/ame localhost and all should %e 'ell ater that.
/o' that "ou have the Apache server runnin&$ activate "our 'e% %ro'ser. -"pe the address 12P.+.+.1
in the address %ar and press enter. 0ver" machine on the internet is kno'n %" a num%er. <e call this
num%er an !2 address. !2 stands or the !nternet 2rotocol. 0ver" machine that has the !nternet sot'are
runnin& is also kno'n %" the num%er 12P.+.+.1 or localhost. !n case a ile called inde8.html e8ists$ the
%ro'ser 'ill displa" it. -his is %ecause it is located in htdocs and is the ile that &ets picked up %"
deault 'hen "ou &ive "our machine address and "ou have Apache runnin&.
Chan&e to the htdocs su%6director" and create an html ile a.html to displa" a orm.
a.9tml
09tml/
03orm/
0in2t tye+s2bmit val2e+Searc9/
03orm/
0N9tml/
-he P)ormQ ta& is used to speci" that 'e are creatin& a orm. Vinput t"peTsu%mit is the s"nta8 or
creatin& a %utton. )alue TSearch means that :Search: is the 'ord that 'ill appear on the %utton. 3ad 'e
said )alue T )i*a"$ "ou 'ould see the :vi*a": on the %utton.
Save the ile as a.html in the htdocs su%director". @o to the %ro'ser 'indo' and t"pe
httpANN12P.+.+.1Na.html in the address %ar and press enter. Gou 'ill no' see a %utton 'ith the name
Search on it. But clickin& on this %utton doesn:t serve an" purpose as o no'.
Het:s alter the pro&ram such that 'hen the user clicks on the Search %utton our CB pro&ram should
e8ecute.
So irst 'e 'ill 'rite our CB pro&ram.
C:\csharp>edit a.cs
/o' t"pe the ollo'in& code.
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine("9i0b/bye");
}
243884333.doc 8L od 221
}
:utput
hiU=>=(e
-his is a simple pro&ram that should displa" hi and %"e. Save the pro&ram as a.cs. .n compilin& the
pro&ram an e8ecuta%le ile :a: is created. ! "ou run the pro&ram as 'e have %een doin&$ "ou 'ill see
the output as &iven a%ove. But remem%er$ 'hat 'e *ust told "ou a%out e8ecuta%les? <hen "ou are
usin& Apache "ou must save all e8ecuta%les in the c&i6%in su%6director" as a securit" precaution.
3ence "ou must cop" a.e8e to c&i6%in %" &ivin& the ollo'in& command.
C:\csharp>cop( a.e/e c:\pro)raL&\apacheL&\apache\c)i*=in
/o' 'e 'ill alter our 3-9H pro&ram. <ithin the orm ta& include actionThttpANN12P.+.+.1Nc&i6
%inNa.e8e -his indicates the action to %e perormed 'hen the %utton is clicked. Since 'e 'ant our
pro&ram a.e8e to run$ 'e have &iven its path.
a.9tml
09tml/
03orm action+9tt=NN'*6.(.(.'Nc;iPbinNa.e?e/
0in2t tye+s2bmit val2e+Searc9/
03orm/
0N9tml/
/o' that 'e have ever"thin& read"$ let:s &et on 'ith the sho'F Activate "our %ro'ser and t"pe
httpANN12P.+.+.1Na.html in the address %ar. Gou see the %utton la%eled Search. /o' click on this %utton.
-o "our horror "ou see an errorF -he %ro'ser 'indo' displa"s an !nternal Server 0rror. /ote the url in
the address %ar6 httpANN12P.+.+.1Nc&i6%inNa.e8e?
/o' make the chan&es as 'e have done %elo'.
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
System.Console.WriteLine("9i0b/bye");
}
}
:utput in <ro@ser
hibye
Save "our ile$ compile it and a&ain cop" it to c&i6%in once a&ain. /o' 'hen "ou run "our pro&ram
rom the %ro'ser$ the error vanishesF And "ou 'ill see hib6e displa"ed. -hat means it is mandator" to
&ive Content6-"pe. !t tells the %ro'ser that 'hat is %ein& sent across is a te8t ile. Also the content is
(ualiied as html and not pure te8t. !t is also called a header. Because 'e are sa"in& html$ the %"e is
displa"ed in %old. So 'e created a ile and the ile &oes over i.e. 'hat ever is in Console.<riteHine
&oes over.
/o' remove html and instead 'rite plain. Het:s see 'hat happens. Ater makin& the necessar" chan&es
and compilin& the pro&ram cop" it a&ain to c&i6%in.
a.cs
class zzz
243884333.doc 8P od 221
{
2blic static void Main()
{
System.Console.WriteLine("ContentPGye=te?tNlain>n");
System.Console.WriteLine("9i0b/bye");
}
}
:utput in <ro@ser
hiU=>=(e
/o' run "our pro&ram rom the %ro'ser. Gou 'ill notice that %"e is not displa"ed in %old. Also note
that no' the ta&s are displa"ed as normal te8t. -he" sho' no ormattin& eects. -his is %ecause
instead o the 'ord html 'e are no' sa"in& plain. -hat means the %ro'ser 'ill no' displa"
ever"thin& as plain te8t.
-hus the Content6-"peA header is used to indicate to the %ro'ser that 'e are sendin& te8t ollo'ed %"
3-9H. -hus i 'e 'ant our pro&ram to e8ecute on the 'e% it is mandator" that 'e include this header
in our pro&ram as the 'e% server does not kno' 'hat is the ile t"pe it is sendin& over.
/o' that 'e have all the in&redients or the inal sho'$ let:s &et on 'ith it. <e 'ill no' add the header
to our &eneral6purpose select pro&ram. <e 'ill do this so that 'e can displa" the contents o a ta%le on
the 'e%. -hus the onl" chan&e that 'e have made to the pro&ram is to add the ollo'in& lineA
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand("select F 3rom abc")s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
89ile ( r.&ead() )
{
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--)
System.Console.Write(r.LetMal2e(i)-" ");
System.Console.WriteLine(Q0br/R);
}
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
243884333.doc 88 od 221
<e have also added S"stem.Console.<riteHine(JV%rUJ)M so that each record is displa"ed on a ne'
line. -he %ro'ser 'ill see V%rU and understand it as an html ta&. -his is %ecause in the header 'e have
speciied te8tNhtml. As such "ou 'ill see each record on a ne' line.
/o' save the ile and compile it. Cop" the ile a.e8e to the c&i6%in su%6director". Activate the %ro'ser
'indo' and t"pe httpANN12P.+.+.1Na.html in the address %ar. /o' click on the search %utton. AccoladesF
Gou have successull" run "our CB pro&ram rom the %ro'ser. Gou 'ill no' see all the contents o the
a%c ta%le. <h" the a%c ta%le? Because that:s the ta%le "ou speciied in "our pro&ram.
-hus$ 'henever the user clicks on the %utton in the %ro'ser he is callin& a pro&ram on the server. -he
server could %e a trillion miles a'a"FF 3o'ever$ even no' ever"thin& is not hunk" dor". -he ma*or
pro%lem %ein& that this entire approach is inle8i%le.
0arlier$ 'e told "ou 'e need this t"pe o pro&rammin& %ecause 'e didn:t 'ant to cop" the pro&rams
on each machine. But the pro%lem 'ith the <e% Server is that i it contains ten html iles then 'e can
&ive the user onl" those ten html iles. So 'e are onl" &ivin& him ten vie's. 3o'ever$ 'hat 'e reall"
need to do is that 'e need to pass data rom us to his machine.
#or e8ample$ let:s assume 'e have a data%ase that has names o people. <e should have a orm in
'hich the user can 'rite the name o a person. <hen he clicks on :ok: that name should &et added to
the data%ase. !n eect$ 'e are addin& one person7s data to the data%ase. Similarl"$ 'e should %e a%le to
delete a person rom the data%ase too. And inall" 'e can have a ta%le6displa" pro&ram 'herein the
user 'ill provide the ta%le name. <hen he clicks on ok$ the contents o that ta%le 'ill %e displa"ed.
-hus "ou can no' think o &eneratin& le8i%le pro&rams. Gou pro%a%l" elt limited earlier as "ou could
displa" contents o onl" that ta%le 'hose name "ou had provided 'ithin the pro&ram.
n'ironmenta! +ariab!es
Beore 'e &et do'n to makin& our pro&rams le8i%le 'e need to understand as to ho' 'e can deal
'ith 0nvironmental )aria%les in CB. An 0nvironmental )aria%le is a 'ord that the operatin& s"stem
understands.
a.cs
class zzz
{
2blic static void Main(){
strin; s;
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
s+System.Bnvironment.LetBnvironmentMariable("$#GH");
System.Console.WriteLine(s);
}
}
:utput
Content*6(pe:te/tNhtml
C:\OIV&..\<>F4 C:\8>FI:8,\M>CR:,:B6.F16\BR+M18:RV\V&.0.0"\4
C:\8>FI:8,4 C:\8>FI:8,\C:MM+FI4 C:\<:R$+FIC\<>F4 C:\8>FI:8,4
C:\8>FI:8,\C:MM+FI4 C:\-R:QR+M B>$1,\M6,
>ispla"s the value o environmental varia%le called 2A-3. An environmental varia%le is a 'ord$
'hich stores a value. <hen "ou &ive the command set 8"KT%"e at the command prompt$ 8"K %ecomes
an environmental varia%le$ 'hich stores the value %"e. All operatin& s"stems allo' "ou to create
environmental varia%les . -he environmental varia%le 2A-3 stores a list o directories that the
operatin& s"stem searches or to ind e8ecuta%les iles. 1un it o the 'e% server or %" itsel.
a.cs
243884333.doc 8D od 221
class zzz
{
2blic static void Main(){
System.Collections."Aictionary i;
i+System.Bnvironment.LetBnvironmentMariables ();
System.Collections."AictionaryBn2merator d;
d+i.LetBn2merator();
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
System.Console.WriteLine(i.Co2nt - "0br/");
89ile (d.MoveJe?t())
{
System.Console.WriteLine("{(}+{'}0br/")d.Sey)d.Mal2e);
}
}
}
-here can %e 1++:s o environmental varia%les and 'e 'ould like a list o all o them. -he class
0nvironment in the S"stem namespace has a unction @et0nvironment)aria%les 'hich returns an
o%*ect that looks like !>ictionar". -his !>ictionar" o%*ect has a unction called @et0numerator 'hich
returns an o%*ect that looks like !>ictionar"0numerator. Gou have to learn all this %" rote$ there is no
other option availa%le. <e are then displa"in& ho' man" environmental varia%les there are %" printin&
a mem%er Count in !>ictionar". -hen 'e need to activate each varia%le %" callin& 9ove/e8t 'hich
returns true i there are more environmental varia%les in the list. An environmental varia%le is
represented %" a ke"6value pair$ 'hich is also varia%le in the !>ictionar"0numerator class. -hus 'e
can displa" all the environmental varia%les startin& 'ith a count o ho' man" there are.
! "ou check the list o environmental varia%les in "our %ro'ser$ "ou 'ill see one called
I;01G\S-1!/@ $ %ut it 'ill have no value.
/o' run as httpANN12P.+.+.1Nc&i6%inNa.e8e?aaTho and see the varia%le I;01G\S-1!/@ have a value
aaTho.
a.9tml
09tml/
03orm action+9tt=NN'*6.(.(.'Nc;iPbinNa.e?e/
0in2t tye+s2bmit val2e+Searc9/
0in2t tye+te?t name+aa/
03orm/
0N9tml/
1un the ile in the %ro'ser. And "ou 'ill no' see a te8t %o8 'hich is internall" called aa. -his is
%ecause o the ta& input t"peTte8t. -"pe ho in the te8t %o8 and click on search. -he ;1H 'ill no'
chan&e to httpANN12P.+.+.1Nc&i6%inNa.e8e?aaTho and the varia%le I;01G\S-1!/@ 'ill have the value
aaTho.
a.9tml
09tml/
03orm action+ 9tt=NN'*6.(.(.'Nc;iPbinNa.e?e /
0in2t tye+s2bmit val2e+Searc9/
0in2t tye+te?t name+aa/
0in2t tye+te?t name+bb/
03orm/
0N9tml/
/o' 'e 'ill see t'o te8t %o8es in 'hich 'e 'ill t"pe in ho and no. Click on Search and the url 'ill
chan&e to httpANN12P.+.+.1Nc&i6%inNa.e8e?aaTho]%%Tno and the varia%le I;01G\S-1!/@ 'ill have
the value aaTho]%%Tno.
243884333.doc D+ od 221
CGI 0rogramming
Het us no' understand 'hat &oes on once a&ain. <hat 'e have %een tr"in& to e8plain to "ou is called
C@! pro&rammin& 'here CGI stands )or Common Gate-a6 Inter)ace. 0ver"one reers to %" its
acron"m rather than its e8panded ull orm. CGI is a means b6 -hich a c!ient i.e. a bro-ser can
send some in)ormation to the -eb ser'er.
/o' t"picall" 'hat happens 'hen 'e land up at a search en&ine? <ell$ 'e 'ant to send the 'e%
server i.e. "ahoo the 'ords that 'e 'ant it to search the internet or. At times 'e are asked to ill up a
orm on the 'e% askin& or some personal details. -he inormation 'e ke" in is sent across to the 'e%
server. Hets start 'ith the a%ove 3-9H ile that makes C@! happen. <e have t'o input ta&s 'hich
have an attri%ute t"peTte8t. -hus 'e see t'o te8t %o8es on our screen. <e 'ill t"pe in them hi and %"e
respectivel". -he third input ta& has a t"peTsu%mit and another attri%ute valueTsearch. -his makes it
into a %utton 'ith the 'ord search 'ritten on it.
/o'$ 'hen 'e click on search ater t"pin& in data in the te8t %o8es$ the %ro'ser kno's that "ou have
clicked on a %utton o t"pe su%mit. So$ it 'ill no' look or a ta& orm $ and 'hen it inds it $ it 'ill
read the attri%ute action. <hatever is the value o action$ it 'ill 'rite it in the address %ar.
!n the address %ar 'e 'rite a 54F or 5ni)orm 4esource Focator or the address o a computer on the
net. !n our speciic case$ our %ro'ser:s address %ar 'ill contain httpANN12P.+.+.1Nc&i6%inNa.e8e. -he
%ro'ser does not stop here. !t then adds a ? to the end o the a%ove ;1H . /o' it looks at ever" te8t
%o8 that 'e have in the orm. -he irst one has %een &iven a name aa and 'e t"pe hi in it. So our ;1H
no' chan&es to httpANN12P.+.+.1Nc&i6%inNa.e8e?aaThi.
!t:s not over "et as 'e have one more te8t %o8 to inish 'ith. -his one is called %% and has %"e in it.
-hus our ;1H no' reads httpANN12P.+.+.1Nc&i6%inNa.e8e?aaThi]%%T%"e. 3he R is used to separate
di))erent parameters. aa and %% are also called parameters. -his url is sent across to the 'e% server.
-he 'e% server is *ust another name or a ile server. !t can onl" send iles across. In this case -e are
as7ing it to run a program ca!!ed a.e1e )rom the cgi,bin sub director6. Ie)ore the -eb ser'er
runs a.e1e. it creates one en'ironmenta! 'ariab!e ca!!ed O54=SS34ING and initia!iEes it to
-hate'er )o!!o-s the 8 i.e. in this case aaMhiRbbMb6e. -he 'e% server no' runs a.e8e. <hat a.e8e
actuall" does is none o its concern. All that is 'ants rom a.e8e is a html ile 'hich the 'e% server
sends %ack to the %ro'ser.
3he -eb ser'er a!so needs at !east one header Content,36pe -hich te!!s it the t6pe o) )i!e being
sent across. Norma!!6 a.e1e -ou!d read the en'ironmenta! 'ariab!e O54=SS34ING. e1tract
the parameters. then read a database. e1tract some 'a!ues )rom it and )ina!!6 create an :3#F
)i!e -hich it -ou!d hand o'er to the -eb ser'er. All in all$ this is ho' the ma&ic o the internet is
%ou&ht a%out.
/o'$ let:s learn some more CB.
a.cs
class zzz
{
2blic static void Main(){
strin; s ;
strin; DE e;
c9arDE c ;
s + "9i+byeTno+bad" ;
c + ne8 c9arD*E;
cD(E + KTK;
cD'E + K+K;
e + s.Slit(c);
3oreac9 ( strin; t in e)
243884333.doc D1 od 221
System.Console.WriteLine(t);
}
}
:utput
hi
=(e
no
=ad
s is a strin& 'hich has %een initialiKed to hiT%"e]noT%ad 'hich looks similar to 'hat
I;01G\S-1!/@ as e8plained earlier looks like. C is an arra" o chars 'hich has t'o mem%ers
initialiKed to ] and T respectivel". -he strin& class has a mem%er Split$ 'hich 'ill split a strin& as per
the delimiters provided as the irst parameters in an arra" o chars. -hus the split unction 'ill take the
strin& s and split it 'henever it sees a ] or a T . !n this case it 'ill result in 4 strin&s. Split returns an
arra" o strin&s 'hich 'e are storin& in an arra" e and usin& oreach to displa" the arra".
/o' lets us create a simple orm %ased 'e% application 'hich 'ill accept a ta%le name and then
displa" the entire ta%le or us.
-he html ile a.html as usual 'ill %e copied to the htdocs su%6director".
a.9tml
09tml/
03orm action+ 9tt=NN'*6.(.(.'Nc;iPbinNa.e?e /
0b/ Bnter Gable Jame 0Nb/
0in2t tye+te?t name+aa/ 0/
0in2t tye+s2bmit val2e+"S9o8 Gable"/
03orm/
0N9tml/
<e 'ill run asA
9tt=NN'*6.(.(.'Na.9tml
.ur CB pro&ram reshl" compiled and copied to the c&i6%in su%director" 'ould no' read asA
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
strin; t;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
strin; DE 2;
c9ar DE v + ne8 c9arD'E;
vD(E + K+K;
2 + t.Slit(v);
strin; 8;
8 + "select F 3rom " - 2D'E;
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
243884333.doc D2 od 221
c+ne8 @leAbCommand(8)s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
89ile ( r.&ead() )
{
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--)
System.Console.Write(r.LetMal2e(i)-" ");
System.Console.WriteLine("0br/");
}
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
At our 'e% orm 'e are asked to 'rite the name o the ta%le. -hen click on the %utton Sho' -a%le.
-he 'e% %ro'ser no' 'rites the ollo'in& ;1H in the address %ar ater 'e 'rote a%c as the name o
our ta%le. httpANN12P.+.+.1Nc&i6%inNa.e8e?aaTa%c. -he Apache <e% Server no' runs a.e8e. a.e8e is
nearl" similar to 'hat 'e 'rote earlier 'ith some minor modiications. t contains the value o the
environmental varia%le I;01G\S-1!/@ . v is an arra" o chars 'ith one mem%er 'hich is our
delimiter :T:. Split 'ill return an arra" o strin&s in u $ in our case aa and a%c 'hich 'ill %e stored in
uW+X and uW1X. 0arlier 'e hard6coded the SIH Select statement. 3ere ' starts 'ith the constant strin&
:Select Y rom : and the name o the ta%le is &ot rom uW1X 'hich in turn &ets its value rom the
environmental varia%le I;01G\S-1!/@. <rite the name o an" ta%le that e8ists in the data%ase in
the te8t %o8 and see ho' "ou have %een a%le to 'e% ena%le "our data on the net.
Hets use the ta%le ta&s to make our data look more appealin& in the %ro'ser.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
strin; t;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
strin; DE 2;
c9ar DE v + ne8 c9arD'E;
vD(E + K+K;
2 + t.Slit(v);
strin; 8;
8 + "select F 3rom " - 2D'E;
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand(8)s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
System.Console.WriteLine("0table border+'(/");
89ile ( r.&ead() )
243884333.doc D3 od 221
{
System.Console.WriteLine("0tr/");
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--) {
System.Console.Write("0td/" - r.LetMal2e(i) - "0Ntd/");
}
System.Console.WriteLine("0Ntr/");
}
System.Console.WriteLine("0Ntable/");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
-he output looks &reat. <e have made ver" small additions to our pro&ram$ mostl" cosmetic. <e start
'ith the ta%le ta& 'ith a %order. -he 'hile &ets called once or ever" record and in this 'hile 'e start
and end 'ith a ro' ta& tr and Ntr. -he or &ets called or ever" ield and here 'e enclose the ield value
'ith a ta& td and Ntd. At the end o the 'hile 'e end 'ith the Nta%le ta&. -he onl" pro%lem is that 'e
have not displa"ed the ield names at all. Het the ne8t pro&ram do so.
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
strin; t;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
strin; DE 2;
c9ar DE v + ne8 c9arD'E;
vD(E + K+K;
2 + t.Slit(v);
strin; 8;
8 + "select F 3rom " - 2D'E;
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;Aata
So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand(8)s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
System.Console.WriteLine("0table border+'(/");
System.Console.WriteLine("0tr/");
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--)
System.Console.WriteLine("0td/" - r.LetJame(i) - "0Ntd/");
System.Console.WriteLine("0Ntr/");
89ile ( r.&ead() )
{
System.Console.WriteLine("0tr/");
3or ( int i + ( ; i 0 r.:ieldCo2nt ; i--) {
System.Console.Write("0td/" - r.LetMal2e(i) - "0Ntd/");
}
System.Console.WriteLine("0Ntr/");
243884333.doc D4 od 221
}
System.Console.WriteLine("0Ntable/");
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
All that 'e did 'as to cop" the or loop 'hich &enerated the ield names rom an earlier pro&ram. <e
put a tr and a Ntr around the or loop and the names o ields are ta&&ed 'ith td. @reat lookin& output.
a.cs
class zzz
{
2blic static void Main()
{
strin; t;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
System.Console.WriteLine(t);
}
}
:utput
aaJselectMSMfromMa=c
!n the ori&inal a.html instead o 'ritin& a simple ta%le name 'e 'rote 4select Y rom a%c7 instead.
When -e disp!a6ed the en'ironment 'ariab!e O54=SS34ING -e !earn that the spaces are
rep!aced -ith a T sign. 3he ru!es o) creating a 54F speci)6 that a space is a )orbidden character
and a!! spaces that -e -rite are rep!aced b6 a T. 3hus -e ha'e to con'ert the T bac7 into spaces.
a.cs
class zzz
{
2blic static void Main()
{
strin; t)s;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
s + t.&elace(K-K)K K);
System.Console.WriteLine(s - "0br/");
System.Console.WriteLine(t);
}
}
:utput
aaJselect S from a=c
aaJselectMSMfromMa=c
-he strin& class has a method called replace 'hich replaces ever" occurrence o the irst parameter i.e.
, 'ith the second i.e. a space. -hus s is t %ut 'ith the plus si&n replaced %" a space.
Hets us kno' 'rite an insert statement 'hich 'ill ask the user to ke" in his irst and last name and
then add it into a ta%le. <e create a ta%le :%%%: in our data%ase 'ith t'o ields 1 and 2 %oth character
t"pe. .ur html ile also no' chan&es to.
243884333.doc DE od 221
a.9tml
09tml/
03orm action+ 9tt=NN'*6.(.(.'Nc;iPbinNa.e?e /
0b/ Bnter Users :irst Jame 0Nb/
0in2t tye+te?t name+aa/ 0/
0b/ Bnter Users Last Jame 0Nb/
0in2t tye+te?t name+bb/ 0/
0in2t tye+s2bmit val2e+"#dd"/
03orm/
0N9tml/
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;
Aata So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
strin; t;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
strin; DE 2;
c9ar DE v + ne8 c9arD*E;
vD(E + K+K;
vD'E + KTK;
2 + t.Slit(v);
strin; 3')3*)3,;
3' + 2D'E.&elace(K-K)K K);
3* + 2D,E.&elace(K-K)K K);
3, + "insert into bbb val2es(K" - 3' - "K)K" - 3* - "K)";
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
System.Console.WriteLine(3,);
c+ne8 @leAbCommand(3,)s);
c.B?ec2teJon%2ery();
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
:utput
insert into === %alues(7%iEa( ram727muDhi7)
CR$ in +ddress <ar.
http:NN&7.0.0.&Nc)i*=inNa.e/eGaaJ%iEa(MramP==JmuDhi
-he irst chan&e is that our arra" o chars is no' t'o mem%ers lar&e and the second delimiter is the
:]:. -hus our I;01G\S-1!/@ 'ill %reak into 4 strin&s aa $ vi*a",ram $ %% and mukhi in uW+X to uW3X.
<e replace the , 'ith the : : in %oth strin&s and d"namicall" &enerate the insert statement. !t looks
conusin& %ut is not$ .nce a&ain 1 and 2 contain the d"namic data %ut %ecause the" are strin&s 'e
need them to %e separated %" a sin&le inverted comma. -hus the complication in concatenatin& strin&s.
243884333.doc DL od 221
-he %ro'ser displa"s the SIH statement that 'ill %e e8ecuted$ %ut in real lie 'e 'ould displa" a
success or error messa&e.
Data Search 0rogram
/o' let us 'rite a search en&ine or more precisel"$ a &eneral purpose data retrieval en&ine. #or 'hich
'e have to irst create a simple data%ase that 'ill contain the ollo'in& ields A
Oe"'ord 6 that 'ill store 'hat the pa&e contains$
url 6 the address o the pa&e$
name 6 to %e displa"ed instead o the url
and inall" the te8t that 'ill %e displa"ed e8plainin& the pa&e.
create table ss ( <ey8ord c9ar('()) 2rl c9ar('(()) name c9ar('(()) descri
c9ar('(());
<e 'ill also add the ollo'in& records.
insert into ss val2es ( K4avaK) Ka.9tmlK) K4ava siteK) K;reat 4ava siteK);
insert into ss val2es ( KcK) Kb.9tmlK) Kc siteK) K;reat c siteK);
insert into ss val2es ( KbasicK) Kc.9tmlK) Kbasic siteK) K;reat basic siteK);
insert into ss val2es ( KcobolK) Kd.9tmlK) Kcobol siteK) K;reat cobol siteK);
Create the ollo'in& html iles in the htdocs su%director"
searc9.9tml
09tml/
03orm action+ 9tt=NN'*6.(.(.'Nc;iPbinNa.e?e /
0b/ Bnter <ey8ord 0Nb/
0in2t tye+te?t name+aa/ 0/
0in2t tye+s2bmit val2e+"Searc9"/
03orm/
0N9tml/
a.9tml
G9e Wle is 3or 4ava
b.9tml
G9e Wle is 3or C
c.9tml
G9e Wle is 3or Basic
d.9tml
G9e Wle is 3or Cobol
-he CB pro&ram 'ill %e as ollo's
a.cs
2sin; System.Aata.@leAb;
class zzz
{
2blic static void Main()
{
try
{
strin; t;
t+System.Bnvironment.LetBnvironmentMariable("%UB&OVSG&"JL");
243884333.doc DP od 221
strin; DE 2;
c9ar DE v + ne8 c9arD'E;
vD(E + K+K;
2 + t.Slit(v);
strin; 8;
System.Console.WriteLine("ContentPGye=te?tN9tml>n");
8 + "select F 3rom ss 89ere <ey8ord+K" - 2D'E - "K";
@leAbConnection s;
s + ne8 @leAbConnection("[email protected].(;Aata
So2rce+c=>>zzz.mdb");
s.@en();
@leAbCommand c;
c+ne8 @leAbCommand(8)s);
@leAbAata&eader r;
r + c.B?ec2te&eader();
89ile ( r.&ead() )
{
System.Console.WriteLine("0a 9re3+N{(}/ {'} 0Na/ {*}
0br/")r.LetMal2e('))r.LetMal2e(*))r.LetMal2e(,));
}
}
catc9(System.B?cetion e)
{
System.Console.WriteLine(e.GoStrin;());
}
}
}
.pen up the %ro'ser and enter the url :httpANN12P.+.+.1Nsearch.html:
All that this pro&ram does is use the concept o a h"perlink to %uild a search en&ine and e8tract data
rom a data%ase. <e assume 'e have a data%ase o a trillion records that map the internet tellin& us the
ke"'ords that each url stands or. -he user ke"s in the name o a lan&ua&e and 'e use the select
statement to etch the records meetin& the condition$ ormat it and then send the html ile across.
<e can use the same concept to ill up a list %o8. -he html ta&s or list %o8 are as ollo's
0select name + aa/
0otion/ bl2e 0Notion/
0otion/ red0Notion/
0otion/ oran;e 0Notion/
0Nselect/
!n a real lie situation$ the colours 'ill %e retrieved rom a data%ase and the 3-9H ile
&enerated %" a C@! pro&ram.
L
9iscellaneous
#u!tip!e )i!es
A CB pro&ram can %e spread over multiple iles. So ar all our code has %een 'ritten in one lar&e ile.
Hets us create 2 .cs iles a.cs and %.cs as ollo's
243884333.doc D8 od 221
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.abc();
}
}
b.cs
2blic class yyy
{
2blic void abc()
{
System.Console.WriteLine("9i");
}
}
0arlier our code did not spa'n multiple iles. CB does not care 'hether the code is in one ile or
spread over multiple iles. <e have onl" to make a small chan&e 'hile 'e compile the pro&ram.
1unnin& Csc a.cs %.cs 'ill create a.e8e
:utput
;i
-hese iles are called source iles and it is a &ood idea to &ive them a ile e8tension o .cs. ! "ou
rename %.cs to %.888 as 'e did and rerun csc as
>csc a.cs =.///
-his 'ill create a.e8e as usual. #ile e8tensions matter to the pro&rammer not to the compiler.
Ascii and 5nicode
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine((c9ar)5.);
System.Console.WriteLine((c9ar)55);
System.Console.WriteLine((c9ar)56);
}
}
:utput
+
<
C
243884333.doc DD od 221
Computers in a -a6 are prett6 dumb. 3he6 do not understand !etters o) the a!phabet. A!! that
the6 can store in memor6 are numbers. Iut then. ho- does a computer understand or disp!a6
a!phabets? -he <riteHine unction displa"s LE as LE$ %ut the output is A. !n the () %rackets 'e have
placed a data t"pe called char. <e call a ( ) a cast. !t means$ or the moment convert 'hatever ollo's
into a char. -hus the num%er LE &ets converted into a char 'hich is displa"ed as a :A:. -he LL &ets
displa"ed as a :B:. Someone$ some'here in the 'orld invented a rule 'hich speciied that the num%er
LE represents a capital A$ etc. -his rule is &iven a name and is called ASC!!. A!! that ASCII sa6s is
that the numbers )orm / to 255 can a!so represent sma!! and capita! !etters. punctuation etc.
<henever "ou 'rite A$ rest assured some'here in memor"$ a LE 'as stored. A ile on disk can also
contain num%ers orm + to 2EE onl" and the same rule as spelt a%ove appl".
a.cs
class zzz
{
2blic static void Main()
{
c9ar i + KaK;
System.Console.WriteLine((c9ar)i);
}
}
:utput
a
CB oers us the data t"pe char to represent ASC!! values naturall".
a.cs
class zzz
{
2blic static void Main()
{
int i;
3or ( i+(; i0+*..; i--)
System.Console.Write(i - " " - (c9ar)i - " ");
}
}
-he a%ove pro&ram displa"s the entire Ascii ta%le. -he pro%lem 'ith Ascii is that it is suicient or a
lan&ua&e like 0n&lish$ 'hich does not have to man" s"m%ols to represent. 3o'ever$ 'hen it comes to
visual lan&ua&es like 5apanese$ the" have more s"m%ols to represent than 0n&lish. Ascii can represent
a ma8 o 2EL uni(ue s"m%ols. 3he industr6 thus in'ented 5nicode -hich uses 2 b6tes )or e'er6
character un!i7e AsciiAs one. All the lan&ua&es o the 'orld can %e represented %" ;nicode. CB
understands ;nicode and thus the char data t"pe store characters internall" as ;nicode and not Ascii.
-he present ;nicode standard is 3.+.
a.cs
class zzz
{
2blic static void Main()
{
int int;
}
}
Compiler 1rror
a.cs(!2!): error C,&0"&: >dentifier e/pected2 7int7 is a De(@ord
243884333.doc 1++ od 221
a.cs(!23): error C,&00&: >dentifier e/pected
Words !i7e int. char. i) etc are reser'ed b6 C< and -e are not a!!o-ed to use them as )unction
names. c!ass names. 'ariab!e names etc. :o-e'er. i) 6ou insist on doing so. then 6ou ha'e to
pre)ace the name -ith a U sign like %elo'.
a.cs
class zzz
{
2blic static void Main()
{
int Xint;
}
}
Compiler 8arnin)
a.cs(!2!): @arnin) C,0&A3: 6he %aria=le 7int7 is declared =ut ne%er used
-he 'arnin& does not name the varia%le @int %ut int.
a.cs
class zzz
{
2blic static void Main()
{
int Xint;
Xint + '(;
System.Console.WriteLine(Xint);
}
}
:utput
&0
<e have millions o names to choose or a varia%le$ then 'h" insist on an int. -here 'ill %e times
'hen another lan&ua&e declares a name as a reserved name and in those cases 'e 'ould use the @
si&n. !t is advisa%le not to use the @ si&n ver" oten.
<hen 'e run the CB compiler on our pro&ram$ it does 2 thin&s. .ne$ it reads our code and converts it
into thin&sNtokens it understands. -his is called a He8ical anal"sis. -hen it does a S"ntactic anal"sis
'hich &ives us an e8ecuta%le output.
Comments
Comments are a orm o documentation. -he" are lines o code 'ritten or our %eneit (the communit"
o pro&rammers) and not or CB:s. !n spite o this$ pro&rammers in &eneral are laK" in 'ritin&
comments. Comments are i&nored %" the compiler.
a.cs
++ %i t%is is comment
class zzz
{
2blic static void Main() ++ allowed %ere
{
+$
. comment over
two lines
243884333.doc 1+1 od 221
$+
}
}
A regu!ar comment starts -ith a LV and ends -ith a VL. -he" can %e spread over multiple lines and
can %e placed an"'here in "our code. An6 !ine beginning -ith a LL is a one !ine comment and as the
name suggests. cannot span mu!tip!e !ines. A sin&le line comment does not have to %e at the
%e&innin& o a line.
scape SeBuences and Strings
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine("9i >nBye>tJo");
System.Console.WriteLine(">>");
}
}
:utput
hi
<(e Fo
\
An escape seBuence is an6thing that starts -ith a N. A Nn means start printin& rom a ne' line and a
Nt means a ta%. -'o %ackslashes convert into a sin&le %ackslash.
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine(X"9i >nBye>tJo");
}
}
:utput
hi \n<(e\tFo
A string is an6thing in doub!e Buotes. A 'erbatim string starts -ith a U sign and all the escape
se(uences are i&nored %" the CB compiler and displa"ed ver%atim.
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine("9i
bye");
}
}
Compiler 1rror
a.cs(!2A): error C,&0&0: Fe@line in constant
a.cs(A2A): error C,&0&0: Fe@line in constant
A string cannot spa-n mu!tip!e !ines.
243884333.doc 1+2 od 221
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine(X"9i
bye");
}
}
:utput
hi
=(e
0!acing an U in )ront o) the string !ets it spa-n mu!tip!e !ines and the spaces sho-n in the
output. ! "ou 'ant the Z to lose its special meanin& in a strin&$ preace that strin& 'ith a @ si&n.
a.cs
class zzz
{
2blic static void Main()
{
strin; a + "bye";
strin; b + "bye";
System.Console.WriteLine(a ++ b);
}
}
:utput
6rue
-he a%ove e8ample displa"s true$ even thou&h the t'o strin&s ma" %e stored in dierent areas o
memor". -he t'o strin&s contain the same characters and hence are similar.
3he 0reprocessor
Ie)ore the C< compi!er can start. a sma!! part o) it ca!!ed the pre,processor )irst acti'ates itse!) .
!t is called the preprocessor as the same concept e8isted in the pro&rammin& lan&ua&e :C:. A!! that the
preprocessor does is that it !oo7s at those !ines beginning -ith a < s6mbo!.
a.cs
/de0ne vi4ay
class zzz
{
2blic static void Main()
{
}
}
-he irst preprocessor directive 'e are learnin& is called deine. -his lets us create a 'ordNvaria%le or
even %etter$ an identiier called vi*a". -he identiier vi*a" has no value other than true.
a.cs
class zzz
{
2blic static void Main()
{
YdeWne vi4ay
243884333.doc 1+3 od 221
}
}
Compiler 1rror
a.cs(!2): error C,&05: Cannot defineNundefine preprocessor s(m=ols after first toDen in file
We cannot use the <de)ine. a)ter 'a!id C< code has been -ritten. 3he6 ha'e to come at the
beginning o) the )i!e.
a.cs
YdeWne vi4ay
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
System.Console.WriteLine("'");
Yendi3
}
}
:utput
&
As a <de)ine creates a 'ariab!e. its 'a!ue can be chec7ed b6 the i) or more precise!6 the <i) -hich
-or7s in the same -a6 as the i) o) C< does. 3hus the <i) is true and a!! code up to the <endi) gets
added to the code.
a.cs
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
System.Console.WriteLine("'");
Yelse
System.Console.WriteLine("*");
Yendi3
}
}
:utput
-he same rules as %eore or an else. 3ere as 'e have not created an identiier called vi*a"$ it &ets a
value o alse and thereore the Bi is alse. !ma&ine a preprocessor identiier as a %oolean varia%le.
<h" use a preprocessor varia%le instead o a normal one?
1un the CB compiler as ollo's on the a%ove pro&ram and o%serve the chan&e in output.
csc /#:vi$ay a.cs
:utput
&
243884333.doc 1+4 od 221
-he output displa"s 1 as the LD compi!er option !ets 6ou create identi)iers at the time o) compi!ing
the program. -his cannot %e done 'ith a normal varia%le. <e can addNsu%tract lots o code orm our
pro&ram$ at the time o compilation.
a.cs
Y2nde3 vi4ay
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
System.Console.WriteLine("'");
Yelse
System.Console.WriteLine("*");
Yendi3
}
}
:utput
As -e are a!!o-ed to create an identi)ier 'i2a6 b6 the de)ine. the unde) does the re'erse. It sets it
to )a!se -hich is the de)au!t in an6 case. As the 'a!ue o) 'i2a6 is )a!se. the e!se gets acti'ated.
3o'ever 'e run the a%ove as csc N>Avi*a" a.cs$ 'e are irst creatin& an identiier vi*a" at the command
line prompt$ then undeinin& it at the irst line in the pro&ram and the output 'ill sho' 2 as %eore.
Gou cannot use the deine or undeine ater real code.
a.cs
YdeWne vi4ay
Y2nde3 vi4ay
Y2nde3 vi4ay
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
System.Console.WriteLine("'");
Yendi3
}
}
2eople are allo'ed to na& "ou as man" times as the" like. 1epetition has %een part o human histor"
since ancient times. Gou are allo'ed to unde as man" times as "ou like even thou&h it makes no
lo&ical sense.
a.cs
YdeWne vi4ay
YdeWne m2<9i
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
Yi3 m2<9i
System.Console.WriteLine("'");
Yendi3
Yendi3
}
243884333.doc 1+E od 221
}
:utput
&
)%.net
Bdeine vi*a"
Bdeine mukhi
Class KKK
2u%lic Shared Su% 9ain()
Bi vi*a"
Bi mukhi
S"stem.Console.<riteHine(J1J)
Bendi
Bendi
0nd Su%
0nd Class
Gou can have as man" Bi:s 'ithin Bi:s. <e call them nested i:s. ! the Bi is true$ then the te8t up to
the Bendi is included.
a.cs
YdeWne vi4ay
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
System.Console.WriteLine("'");
Yelse
int int;
Yendi3
}
}
<e &et no error at all in spite o the act that 'e are not allo'ed to create a varia%le called int. !s CB
sleepin& at the 'heel? !t is not as the preprocessor realiKed that the identiier vi*a" is true$ it removed
all the code rom the Belse to the Bendi. CB did not la& an error at all$ as it 'as not allo'ed to see the
oendin& code %" the preprocessor.
a.cs
class zzz
{
2blic static void Main()
{
Yi3 vi4ay
System.Console.WriteLine("'");
Yelse
int int;
Yendi3
}
}
Compiler 1rror
a.cs(32!): error C,&0"&: >dentifier e/pected2 7int7 is a De(@ord
a.cs(323): error C,&00&: >dentifier e/pected
/o' 'e see the error as the identiier vi*a" is alse. 1emem%er 'hat the CB compiler sees is 'hat the
preprocessor allo's it to. Gou 'rite code and 'hat the compiler sees ma" %e ver" ver" dierent.
243884333.doc 1+L od 221
a.cs
Y8arnin; We 9ave a code red
class zzz
{
2blic static void Main()
{
}
}
Compiler 8arnin)
a.cs(&2&0): @arnin) C,&050: #@arnin): 78e ha%e a code red7
<henever 'e 'ant a 'arnin& messa&e to %e displa"ed at the time o compilin& our code 'e use
B'arnin&.
a.cs
class zzz
{
Y8arnin; We 9ave a code red
2blic static void Main()
{
}
}
Compiler 8arnin)
a.cs(52&0): @arnin) C,&050: #@arnin): 78e ha%e a code red7
;nlike the Bdeine$ the B'arnin& can %e used an"'here in our pro&ram. !t ena%les us to add to the
messa&es o the compiler. Also the line num%er chan&es rom 1 to 3 tellin& us 'here the 'arnin&
occurred.
a.cs
class zzz
{
Yerror We 9ave a code red
2blic static void Main()
{
}
}
Compiler 1rror
a.cs(523): error C,&09: #error: 78e ha%e a code red7
<herever 'e have 'arnin&s$ errors cannot %e ar %ehind. -he dierence is that an error unlike a
'arnin&$ stops ever"thin& in its tracks and does not let the compiler proceed ahead. /o e8e ile is
created. /ormall" an error or 'arnin& 'ould %e placed in an i statement as ollo's.
a.cs
YdeWne vi4ay
YdeWne m2<9i
class zzz
{
Yi3 vi4ay TT m2<9i
Yerror We 9ave a code red
Yendi3
243884333.doc 1+P od 221
2blic static void Main()
{
}
}
Compiler 1rror
a.cs(A23): error C,&09: #error: 78e ha%e a code red7
-he ]] means and. -he i is true i %oth sides o the ]] is true. -he" are in this case. 1emove one o
the a%ove Bdeines and the i 'ill %e alse.
a.cs
Yline '(( "vi4ay"
class zzz
{
Y8arnin; We 9ave a code red
2blic static void Main()
{
}
}
Compiler 8arnin)
%iEa((&02&0): @arnin) C,&050: #@arnin): 78e ha%e a code red7
-he line directive does t'o thin&s. .ne it chan&es the line num%er rom 1 'hich is 'hat is should %e
at the %e&innin& to 1++. -hus the 'arnin& appears on line 1+2 no' and not 2. Also the ile name
chan&es rom a.cs to vi*a". Gou have total control over the line num%er and ile name displa"ed.
a.cs
Yline '(( "vi4ay"
class zzz
{
2blic static void Main()
{
int int;
Yline *(( "m2<9i"
c9ar c9ar;
}
}
Compiler 1rror
%iEa((&0"2!): error C,&0"&: >dentifier e/pected2 7int7 is a De(@ord
%iEa((&0"23): error C,&00&: >dentifier e/pected
muDhi(002A): error C,&0"&: >dentifier e/pected2 7char7 is a De(@ord
muDhi(002&0): error C,&00&: >dentifier e/pected
Hine does not onl" 'ork 'ith the Berror or B'arnin&. !t aects also the compiler:s error line
num%er and ile name. Gou are allo'ed to have as man" Blines as "ou preer.
Section II
P
243884333.doc 1+8 od 221
#unction .verloadin& and !nheritance
!ts not 'hat "ou &et %ut 'hat "ou &ive that makes "ou a richer person. ;nortunatel"$ this little &em is
understood onl" %e a e' and &ivin& remains lar&el" a one 'a" street.
-his chapter e8plains unction overloadin&$ the params parameter and inheritance. <e start 'ith
unction overloadin&.
%unction &'er!oading
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.abc('();
a.abc("bye");
a.abc("no")'(();
}
}
class yyy
{
2blic void abc(int i)
{
System.Console.WriteLine("abc" - i);
}
2blic void abc(strin, i)
{
System.Console.WriteLine("abc" - i);
}
2blic void abc(strin, i1int j)
{
System.Console.WriteLine("abc" - i - 4);
}
}
:utput
a=c&0
a=c=(e
a=cno&00
-he class """ has three unctions$ all o them havin& the same name a%c. -he distinction %et'een
them is in the data t"pes o the parameters. -he" are all dierent. !n CB -e are a!!o-ed to ha'e
)unctions -ith the same name. but ha'ing di))erent data t6pes parameters. -he advanta&e is that
'e call the unction %" the same name as %" passin& dierent parameters$ a dierent unction &ets
called. 3his )eature is ca!!ed )unction o'er!oading. All is ine onl" i the parameter t"pes to the
unction are dierent. <e do not have to remem%er a lar&e num%er o unctions %" name.
3he on!6 reason -h6 )unction o'er!oading -or7s is that C< does not 7no- a )unction b6 name.
but b6 its signature. A signature denotes the )u!! name o) the )unction. 3hus the name o) a
)unction or its signature is the origina! )unction name p!us the number and data t6pes o) its
indi'idua! parameters.
243884333.doc 1+D od 221
a.cs
class zzz
{
2blic void abc()
{
}
2blic int abc()
{
}
2blic static void Main()
{
}
}
Compiler 1rror
a.cs(A2&): error C,0&&&: Class 79997 alread( defines a mem=er called 7a=c7 @ith the same
parameter t(pes
3ere 'e have t'o unctions a%c 'hich dier onl" in the values the" return. As return values do not
count in the unction si&nature and the unction names are similar$ hence the error.
a.cs
class zzz
{
static void abc(int i)
{
}
2blic void abc(int i)
{
}
2blic void abc(strin; )
{
}
2blic static void Main()
{
}
}
Compiler error
a.cs(A2&"): error C,0&&&: Class 79997 alread( defines a mem=er called 7a=c7 @ith the same
parameter t(pes
<e have 2 a%c:s$ that accept an int and dier onl" in the addition o a modiier static. -he" have the
same si&nature as modiiers like static are not considered as part o the unction si&nature. Also$ in the
ne8t pro&ram$ 'e have t'o a%c:s 'ith dierent access modiiers 'hich dier in the parameters$ hence
si&natureNname chan&es causin& an error.
a.cs
class zzz
{
void abc(int i)
{
}
void abc( o2t int i)
{
i + '(;
243884333.doc 11+ od 221
}
void abc( re3 int i)
{
}
2blic static void Main()
{
}
}
Compiler 1rror
Microsoft (R) Visual C# Compiler Version 7.00.9!" #C$R %ersion %&.0.9&"'
Cop(ri)ht (C) Microsoft Corp 000*00&. +ll ri)hts reser%ed.
a.cs(&02A): error C,0AA5: 7a=c7 cannot de%ine overloaded et&ods '&ic& di%%er only on re%
and out
a.cs(A2A): ($ocation of s(m=ol related to pre%ious error)
-he si&nature consists o not onl" the parameter data t"pes$ %ut also the kind o parameters i.e. out re
etc. As unction a%c takes an int 'ith dierent modiiers i.e. out etc$ the si&nature on each is dierent.
3he signature o) a method consists o) its name and number and t6pes o) its )orma! parameters.
3he return t6pe o) a )unction is not part o) the signature. /o t'o unctions can have the same
si&nature and also non6mem%ers cannot have the same name as mem%ers.
A unctionNmethod can %e called %" our dierent t"pes o parameters. -hese are pass %" value$
reerence$ output and inall" parameter arra"s. -he parameter modiier is not part o the unction
si&nature. Hets no' understand 'hat parameter arra"s are all a%out.
0arams 0arameter
A method declaration creates a separate declaration space. -his means that an"thin& created in a
method is lost at the end o the method.
a.cs
2blic class zzz
{
2blic void abc(int i)strin; i) {}
2blic void !r(int i)
{
strin; i;
}
2blic static void Main()
{
}
}
Compiler 1rror
a.cs(525): error C,0&00: 6he parameter name 7i7 is a duplicate
a.cs(A23): error C,0&5A: + local %aria=le named 7i7 cannot =e declared in this scope =ecause it
@ould )i%e a different meanin) to 7i72 @hich is alread( used in a 7parent or current7 scope to
denote somethin) else
0arameter names ha'e to be uniBue. Also$ 'e cannot have a parameter and a varia%le created in a
unction %lock 'ith the same name.
!n pass %" value$ the value o the varia%le is passed. !n the case o re and out$ the address o the
reerence is passed.
243884333.doc 111 od 221
a.cs
2blic class zzz
{
strin; s + "9i";
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
abc(re3 s)re3 s);
System.Console.WriteLine(s);
}
void abc(re3 strin; a) re3 strin; b) {
System.Console.WriteLine(s);
a+"no";
System.Console.WriteLine(s);
b + "yes";
System.Console.WriteLine(s);
s + "maybe";
}
}
:utput
hi
no
(es
ma(=e
Gou are allo'ed to pass the same re parameter as man" times as "ou desire. !n the unction a%c the
strin& s has a value o hi. -hen %" chan&in& the strin& % to no$ 'e are actuall" chan&in& the strin& s to
no as s is passed %" reerence. )aria%les a and s reer to the same strin& in memor". Chan&in& one
chan&es the other. A&ain chan&in& % also chan&es s as the" reer to the same strin&. -hus varia%les a$ %
and s reer to the same strin& in memor".
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
abc(*)"9i")"bye")"no");
abc(*()"9i");
abc(*);
}
void abc(int i ) params strin, 23 b)
{
3oreac9 ( strin; s in b)
System.Console.WriteLine(s - " " - i);
}
}
:utput
hi
243884333.doc 112 od 221
=(e
no
hi 0
<e 'ill encounter a situation 'here 'e 'ould like to pass a varia%le num%er o ar&uments to a
unction. -his is not possi%le as o no' as CB is e8tremel" inick" a%out the num%er and t"pe o data
'e pass to a unction. ! 'e pass a strin& 'here an int is e8pected$ CB starts screamin& like a %a%". I)
-e -ant to pass a 'ariab!e number o) arguments to a )unction. -e ha'e to use a 7e6-ord
params. -his ke"'ord can onl" %e applied to the last parameter. 3here)ore the 'ariab!e number o)
arguments can on!6 come at the end. !n the case o unction a%c$ the irst parameter has to %e an int$
the rest o them can %e rom Kero to an ininite num%er o strin&s.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
void abc(int i ) arams strin; DE b ) int 4)
{
}
}
Compiler 1rror
a.cs(A2&3): error C,05&: + params or WWar)list parameter must =e the last parameter in a
formal parameter list
-he params ke"'ord in this version has to %e at the end onl" as stated a%ove.
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
abc(*),)I);
abc(*()');
abc(*);
}
void abc(int i ) arams int DE b)
{
3oreac9 ( int s in b)
System.Console.WriteLine(s - " " - i); } }
:utput
5
"
& 0
CB is smart enou&h i the penultimate parameter and the params have the same data t"pe. -he irst int
is stored in the varia%le i$ the rest are made part o the arra" %.
a.cs
2blic class zzz
{
243884333.doc 113 od 221
void abc(int i ) arams strin; DEDE b)
{
}
void abc(int i ) arams strin; D)E b)
{
}
}
Compiler 1rror
a.cs(A2A): error C,0!: (&e )aras )araeter ust be a sin!le diensional array
-he data t"pe o the params parameter must %e$ as the error messa&e states$ a sin&le dimensional arra".
-hus WXWX is allo'ed %ut not W$X. Gou are also not allo'ed to com%ine the params ke"'ord 'ith re or
out.
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
strin; DE s + {"9i")"bye")"no"};
abc(*)s);
}
void abc(int i ) arams strin; DE b)
{
3oreac9 ( strin; s in b)
System.Console.WriteLine(s - " " - i);
}
}
:utput
hi
=(e
no
Gou are allo'ed to pass an arra" o strin&s instead o individual strin&s as parameters. 3ere s is an
arra" o strin&s 'hich has %een initialiKed usin& the short orm. !nternall" 'hen 'e call the unction
a%c$ CB converts the arra" o strin&s into individual strin&s.
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
strin; DE s' + {"9i")"bye"};
abc(*)s')"9ell");
}
void abc(int i ) arams strin; DE b)
{
243884333.doc 114 od 221
}
}
Compiler 1rror
a.cs(&&2&): error C,&!0: 6he =est o%erloaded method match for 7999.a=c(int2 params strin)#')7
has some in%alid ar)uments
a.cs(&&27): error C,&!05: +r)ument 77: cannot con%ert from 7strin)#'7 to 7strin)7
9i8in& and matchin& is not allo'ed in CB. <hat 'e assumed CB 'ould do is to add the last strin& hell
to the arra" o strin&s s1 or convert s1 to individual strin&s and then add the strin& hell to it. 2erectl"
lo&ical 'e thou&ht. .nl" i 'ishes 'ere horsesC
!nternall" %eore callin& the unction a%c$ it collects all the individual parameters and converts it into
one %i& arra" or the params statement.
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
int DE a + {')*),};
abc(*)a);
System.Console.WriteLine(aD'E);
}
void abc(int i ) arams int DE b)
{
bD'E + '((;
}
}
:utput
&00
-he output produced is proo o concept. -he arra" mem%er aW1X has an initial value o 2 and in the
unction a%c 'e chan&e it to 1++. -he ori&inal chan&es$ this means that the arra" is &iven to the
unction a%c.
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
int a + '(;
abc(*)'(()a)*();
System.Console.WriteLine(a);
}
void abc(int i ) arams int DE b)
{
bD'E + '((;
243884333.doc 11E od 221
}
}
:utput
&0
!n this case CB creates an arra" containin& 1++ 1+ and 2+. <e are chan&in& the second mem%er to 1++
'hich has nothin& to do 'ith the varia%le a. As a%c has no kno'led&e o a$ ho' on earth can a%c
chan&e the value o the int a? -hus it sta"s the same.
a.cs
2blic class zzz
{
2blic static void Main()
{
zzz z + ne8 zzz();
z.!r();
}
void !r()
{
abc(*);
abc(*),);
abc(*),).)5);
}
void abc(int i) int 4)
{
System.Console.WriteLine("t8o ints "- i - " " - 4);
}
void abc(arams int DE a)
{
System.Console.WriteLine("arams a");
}
}
:utput
params a
t@o ints 5
params a
3ere 'e are discussin& unction overloadin&. CB is e8tremel" %ri&ht thou&h partial. !t does not like the
params statement and treats it like a stepchild. <hen 'e call a%c 'ith one int$ CB can onl" call the a%c
that takes a params as a parameter as it matches one int. An arra" can contain one mem%er. -he un
starts 'ith the a%c that is %ein& called 'ith t'o ints. 3ere 'e have a dilemma. CB can call the params
a%c or the a%c 'ith t'o ints. As mentioned earlier$ CB treats the params as a second class citiKen and
thereore chooses the a%c 'ith t'o ints. <hen there are more than t'o ints like in the third invocation$
CB has no choice %ut to &rud&in&l" choose the a%c 'ith the params. CB chooses the params as a last
resort %eore la&&in& an error.
a.cs
2sin; System;
class zzz
{
static void Z(arams ob4ectDE b) {
3oreac9 (ob4ect o in b) {
Console.Write(o.LetGye().:2llJame - " ");
}
Console.WriteLine();
}
243884333.doc 11L od 221
static void Main() {
ob4ectDE a + {') "Hello") '*,.I.5};
ob4ect o + a;
Z(a);
Z((ob4ect)a);
Z(o);
Z((ob4ectDE)o);
}
}
:utput
,(stem.>nt5 ,(stem.,trin) ,(stem.Iou=le
,(stem.:=Eect#'
,(stem.:=Eect#'
,(stem.>nt5 ,(stem.,trin) ,(stem.Iou=le
!n the irst case 'e are passin& the unction an arra" o o%*ect that looks like o%*ect. <e 'ill tell "ou
a little later that all classes are derived rom o%*ect. -he unction receives an arra" o o%*ects %. !n
the oreach 'e kno' that the o%*ect class has a unction @et-"pe that returns an o%*ect that looks like
-"pe$ 'hich in turn has a unction called #ull/ame 'hich returns the name o the t"pe. <e see three
dierent t"pes displa"ed. !n the second invocation o 'e are castin& a to an o%*ect. -here is no
conversion availa%le rom convertin& an o%*ect to an o%*ect arra" i.e. o%*ect WX. -hereore a one
element o%*ect WX is created. !t:s the same case in the third invocation and the last e8plicitl" casts to an
o%*ect arra".
a.cs
2sin; System;
class zzz
{
static void Z(arams ob4ectDE b) {
Console.WriteLine(b.LetGye().:2llJame);
Console.WriteLine(b.Len;t9);
Console.WriteLine(bD(E);
}
static void Main() {
ob4ectDE a + {') "Hello") '*,.I.5};
Z((ob4ect)a);
}
}
:utput
,(stem.:=Eect#'
&
,(stem.:=Eect#'
Inheritance
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
a.abc();
}
}
class yyy
{
243884333.doc 11P od 221
2blic int i + '(;
2blic void abc()
{
System.Console.WriteLine("yyy abc");
}
2blic void !r()
{
System.Console.WriteLine("yyy !r");
}
}
class ???
{
}
Compiler 1rror
a.cs(A2&): error C,0&&7: 7///7 does not contain a definition for 7a=c7
-he class """ contains 2 unctions and one instance varia%le. -he class 888 contains no code and no
varia%les at all. An empt" class does not denote an" error as 'e are a%le to instantiate an o%*ect that
looks like 888. -he error comes a%out %ecause the class 888 has no unction called a%c. 3o'ever the
class """ has a unction a%c. <ould it not %e &reat i 'e 'ere allo'ed to use all the code in the class
""" rom 888. 0asier said than done$ 'e &uessF
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
a.abc();
}
}
class yyy
{
2blic int i + '(;
2blic void abc()
{
System.Console.WriteLine("yyy abc");
}
2blic void !r()
{
System.Console.WriteLine("yyy !r");
}
}
class ??? = yyy
{
}
:utput
((( a=c
-he error disappears and the a%c in """ &ets e8ecuted. ! ater the name o the class "ou 'rite A """
i.e. the name o another class$ a lot happens at once. 888 is no' said to have %een derived rom """.
<hat that means is all the code 'e 'rote in """ can no' %e used in 888. !t is i 'e actuall" 'rote all
the code that is contained in """ in 888. ! 'e had created an o%*ect that looks like """$ ever"thin& that
the o%*ect could do$ no' an o%*ect that looks like 888 can also do. But 'e have not 'ritten a line o
code in 888. <e are made to %elieve that 888 has one varia%le i and t'o unctions a%c and p(r as """
contains these t'o unctions. 3ere 'e are teachin& "ou the concepts o inheritance 'here """ 'ill
no' %e called the %ase class$ 888 the derived class.
243884333.doc 118 od 221
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
a.abc();
}
}
class yyy
{
2blic int i + '(;
2blic void abc()
{
System.Console.WriteLine("yyy abc");
}
2blic void !r()
{
System.Console.WriteLine("yyy !r");
}
}
class ??? = yyy
{
2blic void abc()
{
System.Console.WriteLine("??? abc");
}
}
Compiler 8arnin)
a.cs(52&5): @arnin) C,0&03: 6he De(@ord ne@ is reHuired on 7///.a=c()7 =ecause it hides
inherited mem=er 7(((.a=c()7
:utput
/// a=c
/othin& in the 'orld stops class 888 rom creatin& a unction a%c i.e. one 'ith the same name as in the
%ase class . CB simpl" &ives us a 'arnin&. <hen 'e run a.a%c()$ CB irst checks 'hether the class 888
(as a looks like 888) has a unction called a%c. ! it does not$ then it 'ill check in the %ase class. 0arlier
a%c 'as onl" availa%le in the %ase class and hence &ot e8ecuted. 3ere as it is alread" there in 888$ it
&ets called rom 888 and not """. 1emem%er the derived classes &et a irst shot at e8ecution$ then the
%ase class. -he reason %ein&$ the %ase class ma" have a num%er o unctions and or various reasons
"ou ma" not %e satisied 'ith 'hat the" do. Gou should have the ri&ht to have "our cop" o the
unction to %e called. !n other 'ords the derived classes unctions override the ones in the %ase class.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
a.abc();
}
}
class yyy
{
2blic int i + '(;
2blic void abc()
243884333.doc 11D od 221
{
System.Console.WriteLine("yyy abc");
}
2blic void !r()
{
System.Console.WriteLine("yyy !r");
}
}
class ??? = yyy
{
2blic void abc()
{
System.Console.WriteLine("??? abc");
base.abc();
}
}
:utput
/// a=c
((( a=c
<hat i "ou 'ant the %est o %oth 'orlds? Gou ma" 'ant to call the %ase classes a%c irst and then
"ours or vice versa. -o accomplish this$ CB &ives "ou a reserved 'ord$ somethin& ree called %ase. -he
'ord %ase can %e used in an" derived class. !t means call the unction o the %ase class. Simple. -hus
%ase.a%c 'ill call the unction a%c rom """ the %ase class o 888.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
a.abc();
}
}
class yyy
{
2blic int i + '(;
2blic void abc()
{
System.Console.WriteLine("yyy abc");
}
2blic void !r()
{
System.Console.WriteLine("yyy !r");
}
}
class ??? = yyy
{
2blic void abc()
{
System.Console.WriteLine("??? abc");
base.!r();
}
}
:utput
/// a=c
((( pHr
243884333.doc 12+ od 221
-here is onl" one small chan&e made to the pro&ram and that is %ase.a%c is replaced %" %ase.p(r. !n
this case the unction p(r rom the class """ &ets called. Base is ver" &eneral purpose. !t lets "ou
access mem%ers o the %ase class rom the derived class. Gou cannot use %ase in """ as """ is not
derived rom an" class. -hus %ase can onl" %e used in derived classes.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.?yz();
}
}
class yyy
{
2blic void abc()
{
System.Console.WriteLine("yyy abc");
}
}
class ??? = yyy
{
2blic void ?yz()
{
}
}
Compiler 1rror
a.cs(A2&): error C,0&&7: 7(((7 does not contain a definition for 7/(97
!n this case$ 888 is derived rom """ and not vice versa. -hus 888 can use all the mem%ers o """.
!nheritance does not 'ork %ack'ards. <hatever mem%ers 888 comprises do not permeate up'ards to
""". Class 888 ma" no' have a unction 8"K %ut it cannot &ive it to class """ and thus an error occurs.
A class inherits ever"thin& rom its %ase class e8cept the constructors and destructors. ! a class c is
derived rom class %$ 'hich in turn has %een derived rom class a$ class c inherits all the mem%ers
declared in class % and also class a. -his concept is called transitive. A derived class can inherit all the
mem%ers o the %ase class %ut cannot su%tract or remove mem%ers o that %ase class. A derived class
can hide mem%ers o the %ase class %" creatin& unctions %" the same name. -he ori&inal mem%er in
the %ase class remains unchan&ed and unaected %" 'hatever is happenin& in the derived class. !t
remains unchan&ed in the %ase class$ it is simpl" not visi%le in the derived class.
A class mem%er can either %e a static mem%er %elon&in& to the class or an instance mem%er %elon&in&
to the instance i.e. accessi%le throu&h the o%*ect and not the class. -he deault is non6static.
A class is also called a data structure. !t consists o data mem%ers like constants$ ields and events and
unction mem%ers like methods$ properties$ inde8ers$ operators$ constructors$ static constructors and
destructors. A class 'ithin a class is called a nested class. -hus 'e can place 11 dierent t"pes o
entities in a class. #unction mem%ers are the onl" mem%ers o a class that contain e8ecuta%le code. A
class creation creates a ne' declaration space.
All classes derive rom o%*ect . .%*ect is the mother o all classes.
a.cs
2blic class zzz = ob4ect
243884333.doc 121 od 221
{
2blic static void Main()
{
}
}
! "ou do not derive rom an" class$ then the CB compiler automaticall" adds Ao%*ect to "our class
deinition. .%*ect$ the onl" class to have this eature is not derived rom an" class. !t is the ultimate
%ase class o all classes in the CB hierarch".
class aa
{
}
class bb = aa
{
}
Class aa is the %ase class o %% . -he documentation ho'ever calls aa the direct %ase class o %%. -hus
the %ase classes o %% are aa and o%*ect.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
class aa = System.Aele;ate
{
}
class bb = System.Bn2m
{
}
class cc = System.#rray
{
}
class dd = System.Mal2eGye
{
}
Compiler 1rror
a.cs(727): error C,0A"": 7aa7 cannot inherit from special class 7,(stem.Iele)ate7
a.cs(&027): error C,0A"": 7==7 cannot inherit from special class 7,(stem.1num7
a.cs(&527): error C,0A"": 7cc7 cannot inherit from special class 7,(stem.+rra(7
a.cs(&A27): error C,0A"": 7dd7 cannot inherit from special class 7,(stem.Value6(pe7
Gou cannot derive a class rom the a%ove 4 classes as the" are special.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
class aa
{
}
class bb
243884333.doc 122 od 221
{
}
class cc = aa) bb
{
}
Compiler 1rror
a.cs(92&A): error C,0!7: 7==7 : t(pe in interface list is not an interface
A class can onl" %e derived rom one more class . Gou are not permitted to derive rom t'o or more
classes i.e. multiple inheritance is not supported. -hus ever" class has one and onl" one %ase class.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
class aa = bb
{
}
class bb = cc
{
}
class cc = aa
{
}
Compiler 1rror
a.cs(&527): error C,0&"A: Circular =ase class definition =et@een 7cc7 and 7aa7
class aa is derived rom %%. Class %% in turn is derived rom cc and cc is derived rom aa. -his results
in a circular deinition. class aa is derived rom %% and cc$ as %% is derived rom cc. As cc is also
derived rom aa class$ %% also derives rom this class 'hich is aa. -hus aa is derived rom aa 'hich is
a lo&ical impossi%ilit".
Buating &b2ects
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
??? b + ne8 ???();
a + b;
b + a;
}
}
class yyy
{
2blic int i+'(;
}
class ??? {
2blic int 4+'(;
243884333.doc 123 od 221
}
Compiler 1rror
a.cs(72!): error C,009: Cannot implicitl( con%ert t(pe 7///7 to 7(((7
a.cs(32!): error C,009: Cannot implicitl( con%ert t(pe 7(((7 to 7///7
CB has a ver" simple rule. !t does not like "ou to e(uate dierent o%*ects to each other. -hus an o%*ect
that looks like """ cannot %e e(uated to one that looks like 888 and vice versa. -hus the error. Another
e8ample 6 "ou cannot take an int and e(uate it to a strin& . CB is e8tremel" strict 'hen it comes to
dealin& 'ith dierent data t"pes.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
??? b + ne8 ???();
a + b;
b + a;
}
}
class yyy
{
2blic int i+'(;
}
class ??? = yyy
{
2blic int 4+'(;
}
Compiler 1rror
a.cs(32!): error C,009: Cannot implicitl( con%ert t(pe 7(((7 to 7///7
-here is ho'ever one 'a" out. .n account o this 'a"$ one o the errors disappeared. -he onl" time
'e are allo'ed to e(uate dissimilar data t"pes is 'hen 'e derive rom them. Hets e8plain this in detail.
<hen 'e create an instance o """ %" sa"in& ne'$ 'e are creatin& t'o o%*ects at one &o$ one that
looks like """ and the other that looks like o%*ect. All classes in CB are inall" derived rom o%*ect. As
888 is derived rom """$ 'hen 'e sa" ne' 888$ 'e are creatin& 3 o%*ects$ one that looks like """$ one
that looks like 888 and inall" o%*ect.
-hus 'hen 'e 'rite a T %$ % looks like 888$ """ and o%*ect and as a looks like """$ there is a match at
""". Conse(uence? /o error. 0ven thou&h a and % have the same values$ usin& a 'e can onl" access
the mem%ers o """$ even thou&h had 'e used % 'e could access 888 also. <e have devalued the
potenc" o a . -he error arises at % T a$ %ecause the class """ is lessNsmaller than the class 888 . -he
class 888 has """ and more. <e cannot have a lar&er class on the ri&ht and a smaller class on the let. a
onl" represents a """ 'hereas % e8pects a 888 'hich is a 888 and """. -he %asic rule is that 'e can
onl" e(uate dissimilar o%*ects i the" are derived rom each other. Gou can e(uate an o%*ect o a %ase
class to a derived class %ut not vice versa.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
243884333.doc 124 od 221
??? b + ne8 ???();
a + b;
b + (???) a;
}
}
class yyy
{
2blic int i+'(;
}
class ??? = yyy
{
2blic int 4+'(;
}
-hou&h 'e %roke a CB rule on e(uatin& o%*ects$ 'e did not &et an error %ecause o the cast . A () is
called a cast. <ithin the %rackets 'e put the name o a class. A cast is the &reat leveler. <hen 'e 'rite
% T a$ CB e8pects the ri&ht hand side o the e(ual to to %e a % i.e. a 888 . !nstead it inds a i.e. a """ .
So %" appl"in& a cast$ 'e are or the moment convertin& the """ o%*ect into an 888. -his strate&"
satisies the rules o CB on onl" e(uatin& similar o%*ects. 1emem%er it is onl" or the duration o the
line that a %ecomes a 888 and not a """.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
??? b + ne8 ???();
a + (yyy) b;
b + (???) a;
}
}
class yyy
{
2blic int i+'(;
}
class ???
{
2blic int 4+'(;
}
Compiler 1rror
a.cs(72A): error C,0050: Cannot con%ert t(pe 7///7 to 7(((7
a.cs(32A): error C,0050: Cannot con%ert t(pe 7(((7 to 7///7
;nortunatel" castin& 'orks onl" i one o the t'o classes is derived rom the other. Gou cannot cast
an" t'o o%*ects to each other.
a.cs
class zzz
{
2blic static void Main()
{
int i + '(;
c9ar 4 + K#K;
i + 4;
4 + i;
}
}
243884333.doc 12E od 221
Compiler 1rror
a.cs(32!): error C,009: Cannot implicitl( con%ert t(pe 7int7 to 7char7
<e are allo'ed to convert a char into a int as i T * %ut not the other 'a" round as * T i.
}
}
:utput
&0
A constant or const varia%le %ehaves as a varia%le. <e &ive it an initial value and can use it 'herever
'e can use a varia%le.
a.cs
2blic class zzz
{
const int i + '(;
2blic static void Main()
{
i--;
System.Console.WriteLine(i);
i + ,(;
}
}
Compiler 1rror
a.cs(A2&): error C,0&5&: 6he left*hand side of an assi)nment must =e a %aria=le2 propert( or
inde/er
a.cs(32&): error C,0&5&: 6he left*hand side of an assi)nment must =e a %aria=le2 propert( or
inde/er
;nlike a varia%le$ 'e are not allo'ed to chan&e the value o a const. -he chan&e is an assi&nment
statement.
a.cs
2blic class zzz
{
const int i ;
2blic static void Main()
{
i + ,(;
System.Console.WriteLine(i);
}
}
Compiler 1rror
a.cs(52&5): error C,0&"!: + const field reHuires a %alue to =e pro%ided
<e have to initialiKe the const varia%le at the time o creation. <e are not allo'ed to initialiKe it later
in our pro&ram.
a.cs
2blic class zzz
{
const int i + 4 - I;
const int 4 + < P ';
const int < + ,;
243884333.doc 12L od 221
2blic static void Main()
{
System.Console.WriteLine(Q{(} {'} {*}R)i)4)<);
}
}
:utput
A 5
A constant can depend upon another constant. CB is smart enou&h to realiKe that to calculate the value
o const i$ it irst needs to kno' the value o *. *7s value depends upon another const k$ 'hose value is
3. -hus CB irst evaluates k to 3 then * %ecomes 2 i.e. k 61 and inall" i takes on the value o * i.e. 2 , 4
resultin& in L.
Hike classes const7s cannot %e circular i.e.$ the" cannot depend upon each other.
a.cs
2blic class zzz
{
const int i + 4 - I;
const int 4 + < P ';
const int < + i;
2blic static void Main()
{
System.Console.WriteLine(Q{(} {'} {*}R)i)4)<);
}
}
Compiler 1rror
a.cs(52&&): error C,0&&0: 6he e%aluation of the constant %alue for .999.i0 in%ol%es a circular
definition
-he value o the const i depends upon * 'hich in turn depends upon k$ 'hich is e(ual to i. -his
%ecomes a circular deinition. A const is a varia%le 'hose value cannot %e chan&ed %ut 'hose initial
value is compile time determined.
a.cs
2blic class zzz
{
2blic const aa a + ne8 aa();
2blic static void Main()
{
}
}
2blic class aa
{
}
Compiler 1rror
a.cs(52&7): error C,0&55: 6he e/pression =ein) assi)ned to .999.a0 must =e constant
a.cs
2blic class zzz
{
2blic const aa a + n2ll;
2blic static void Main()
{
}
}
243884333.doc 12P od 221
2blic class aa
{
}
-he error vanishes as 'e are no' initialiKin& a to an o%*ect 'hich has a value that can %e determined
at compile time. <e cannot ever chan&e the value o a$ so it 'ill al'a"s %e null. /ormall" 'e do not
have consts as a reerence t"pe as the" have value onl" at runtime.
As mentioned earlier 'e can onl" initialiKe a const to a compile time value i.e. a value availa%le to the
compiler 'hile it is e8ecutin&. ne' unortunatel" &ets e8ecuted at runtime and thereore has no value
at compile time. -his &ives us an error.
a.cs
class zzz
{
2blic static void Main()
{
yyy y + ne8 yyy();
System.Console.WriteLine(y.i);
}
}
class yyy {
2blic const int i + ,;
}
Compiler 1rror
a.cs(A2A): error C,0&7A: ,tatic mem=er 7(((.i7 cannot =e accessed @ith an instance
reference4 Hualif( it @ith a t(pe name instead
A constant is static %" deault and 'e cannot use the instance reerence i.e. a name to reerence a
const. A const has to %e static as no one is allo'ed to make an" chan&es to a const.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class yyy
{
2blic static const int i + ,;
}
Compiler 1rror
a.cs(92!): error C,0!0": 6he constant .(((.i0 cannot =e marDed static
CB does not 'ant us to repeat the o%vious over and over a&ain. 5ust like humans$ pro&rammin&
lan&ua&e too have their o'n (uirks. Some other time$ perhaps$ CB ma" permit us to 'rite a static
%eore an entit" that is alread" static %" deault.
a.cs
class zzz
{
2blic static void Main()
{
System.Console.WriteLine(yyy.i - Q Q - ???.i);
}
243884333.doc 128 od 221
}
class yyy
{
2blic const int i + ,;
}
class ??? = yyy
{
2blic const int i + ,(; }
Compiler 8arnin)
a.cs(&"2&3): @arnin) C,0&03: 6he De(@ord ne@ is reHuired on .///.i0 =ecause it hides
inherited mem=er .(((.i0
:utput
5 50
<e can create a const 'ith the same name as another const in the %ase class. -he const o the class 888
i 'ill hide the const i in class """ or the class 888 onl".
%ie!ds
A ield to start 'ith is another 'ord or a varia%le in a class. -here are a lar&e num%er o &eneric rules
that appl" to all mem%ers o a class and 'e 'ill not tire "ou %" repeatin& them ad nauseam.
A varia%le can never have an uninitialiKed value in CB.
a.cs
2blic class zzz
{
static int i;
static bool 4;
2blic static void Main()
{
System.Console.WriteLine(zzz.i - Q Q - zzz.4 );
} }
:utput
0 Balse
Static varia%les are initialiKed 'hen the class is loaded irst. An int is &iven an initial value o Kero and
a %ool #alse.
a.cs
2blic class zzz
{
int i;
bool 4;
2blic static void Main()
{
zzz a + ne8 zzz();
System.Console.WriteLine(a.i - Q Q - a.4 );
} }
:utput
0 Balse
An instance varia%le is initialiKed at the time o creation. -he ke"'ord ne' 'ill create an instance o
the KKK. !t 'ill allocate memor" or each o the non static varia%les and then initialiKe each o them to
their deault values.
243884333.doc 12D od 221
a.cs
2blic class zzz
{
static int i + 4 - '(;
static int 4 + i - ';
2blic static void Main()
{
System.Console.WriteLine(zzz.i - Q Q - zzz.4 );
}
}
:utput
&0 &&
.utputs make a lot o sense i "ou understand them in plain simple 0n&lish. CB al'a"s initialiKes
static ields to their initial value ater creatin& them . )aria%les i and * are thus &iven a deault o Kero.
-hen CB realiKes that these varia%les need to %e assi&ned some values. !t does not read all the lines$
onl" one at a time. !t 'ill no' read the irst line and as the varia%le * has a value o +$ i 'ill &et a value
o 1+. -hen at the ne8t line$ * is the value o i plus 1. -he varia%le i has a value o 1+ and * no'
%ecomes 11. As it does not see %oth lines at the same time$ it does not notice the circularit" o the
a%ove deinition. !n short$ thou&h the a%ove e8ample 'orks$ it is ro'ned upon %" the po'ers to %e at
CB.
a.cs
2blic class zzz
{
int i + 4 - '(;
int 4 + i - ';
2blic static void Main()
{
}
}
Compiler 1rror
a.cs(529): error C,05A: + field initiali9er cannot reference the nonstatic field2 method2 or
propert( .999.E0
a.cs("29): error C,05A: + field initiali9er cannot reference the nonstatic field2 method2 or
propert( .999.i0
!t does not 'ork or instance varia%les as the rules o an instance varia%le are dierent than that o
static. -he ield initialiKer o an instance varia%le has to %e determined at the time o creation o the
o%*ect. -he varia%le * does not have a value at this point in time. !t cannot reer to varia%les o the
same instance at the time o creation. -hus 'e can reer to no instance mem%ers to initialiKe an
instance mem%er. -e8tual order means irst come irst served.
4eadon!6 %ie!ds
#ields can %e also ta&&ed 'ith the modiier readonl".
a.cs
2blic class zzz
{
2blic static readonly int i + '(;
2blic static void Main()
{
System.Console.WriteLine(i);
}
243884333.doc 13+ od 221
}
:utput
&0
/o errors at all. 3o'ever$ remem%er i 'e use a non static varia%le in a static unction 'e 'ill &et an
error.
a.cs
2blic class zzz
{
2blic static readonly int i + '(;
2blic static void Main()
{
i + *(;
System.Console.WriteLine(i);
}
}
Compiler 1rror
a.cs(A2&): error C,0&93: + static readonl( field cannot =e assi)ned to (e/cept in a static
constructor or a %aria=le initiali9er)
Gou cannot chan&e the value o a readonl" ield ater its %ein& &iven an initial value.
a.cs
2blic class zzz {
2blic static readonly int i ;
2blic static void Main() {
}
}
;nlike a const$ a readonl" ield does not have to %e initialiKed at the time o creation.
a.cs
2blic class zzz
{
2blic static readonly int i ;
static zzz()
{
i + *(;
System.Console.WriteLine(Q"n ConstR);
}
2blic static void Main()
{
System.Console.WriteLine(i);
}
}
:utput
>n Const
0
A static readonl" ield can %e initialiKed in a static constructor also. -his is the ma*or dierence
%et'een a const and a readonl" ield.
a.cs
2blic class zzz
{
243884333.doc 131 od 221
2blic readonly aa a + ne8 aa();
2blic static void Main()
{
}
}
2blic class aa
{
}
-he same e8ample 'hich &ave an error 'ith const does not &ive an error 'ith readonl". -o sum up a
readonl" is a more &eneric const and it makes our pro&rams more reada%le as 'e reer to a name and
not a num%er. !s 1++ more intuitive or priceocopper easier to understand? -he compiler 'ould or
reasons o eicienc" convert all const7s and readonl" varia%les to the actual values.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
2blic class aa
{
2blic int readonly i + '(;
}
Compiler 1rror
a.cs(92&): error C,&!3!: Mem=er modifier .readonl(0 must precede the mem=er t(pe and
name
a.cs(925): error C,&!&9: >n%alid toDen .J0 in class2 struct2 or interface mem=er declaration
<herever "ou can place multiple modiiers$ remind "oursel that there are rules that decide the order
o modiiers$ 'hich comes irst. 3ere the readonl" modiier precedes the data t"pe int. .nce a&ain$ no
&reat cosmic la' responsi%le$ *ust a rule that must %e remem%ered.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
2blic class aa {
2blic readonly int i + '(;
void abc(re3 int z)
{
}
void !r()
{
abc(re3 i);
}
}
Compiler 1rror
a.cs(&529): error C,0&9: + readonl( field cannot =e passed ref or out (e/cept in a
constructor)
243884333.doc 132 od 221
A readonl" ield cannot %e chan&ed %" an"one e8cept a constructor. -he unction a%c e8pects
a re parameter 'hich i "ou have or&otten allo's "ou to chan&e the value o the ori&inal.
-hus CB does not permit a readonl" as a parameter to a unction that accepts a re or a out
parameters.
{
}
}
class bbb = aaa
{
2blic override int !r()
{
}
}
Compiler 1rror
a.cs(&32&): error C,0!03: .===.pHr()0: cannot chan)e return t(pe @hen o%erridin) inherited
mem=er .aaa.pHr()0
<hen "ou are overridin& an a%stract unction rom a derived class$ "ou cannot chan&e the parameters
passed to it or the return t"pe. ! the a%stract class has E unctions$ the class derived rom it should also
implement the same E unctions 'ithout chan&in& return t"pe andNor parameters passed to it.
a.cs
2blic class zzz
{
2blic static void Main()
{
ne8 bbb();
}
}
abstract class aaa
{
abstract 2blic void !r();
abstract 2blic void !r'();
abstract 2blic void !r*();
2blic int i;
2blic void abc()
{
}
}
class bbb = aaa
{
2blic override void !r()
{
}
}
Compiler 1rror
a.cs(&327): error C,0!5": .===0 does not implement inherited a=stract mem=er .aaa.pHr&()0
a.cs(&327): error C,0!5": .===0 does not implement inherited a=stract mem=er .aaa.pHr()0
-he error &oes a'a" i 'e implement unctions p(r1 and p(r2 in %%%.
An a%stract class implies that the class is incomplete and cannot %e directl" used. !t can onl" %e used
as a %ase class or other classes to derive rom. 3ence 'e &et a error i 'e use ne' on an a%stract
class. ! 'e do not initialiKe a varia%le in an a%stract class$ it 'ill have a value o + 'hich is 'hat the
compiler kept 'arnin& us a%out. <e can initialiKe i to an" value 'e 'ant. -he varia%les have the same
use and meanin& in an a%stract class like an" other class. <henever a class is incomplete i.e. 'e do not
243884333.doc 133 od 221
have the code or certain unctions$ 'e make those unctions a%stract and the class a%stract . -his
ena%les us to compile the class 'ithout errors. .ther classes can then derive rom our incomplete class
%ut the" have to implement the a%stract i.e. our incomplete unctions. A%stract thus ena%les us to 'rite
code or part o the class and allo's the others to complete the rest o the code.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
class aaa
{
abstract 2blic void !r();
2blic int i + *(;
2blic void abc()
{
}
}
Compiler 1rror
a.cs(92): error C,0!&5: .aaa.pHr()0 is a=stract =ut it is contained in nona=stract class .aaa0
! a class has even one a%stract unction$ then the class has to %e declared a%stract. An a%stract method
cannot also use the modiiers static or virtual.
.nl" in the a%stract class can 'e have one a%stract unction. An"one 'ho implements rom an a%stract
class has to 'rite the code or its unction. B" deault the modiier ne' &ets added$ 'hich makes it a
ne'Ndierent unction.
a.cs
class zzz
{
2blic static void Main()
{
}
}
abstract class yyy
{
2blic abstract void abc();
}
class ??? = yyy
{
2blic override void abc()
{
base.abc();
}
}
Compiler 1rror
a.cs(&!2&): error C,00!: Cannot call an a=stract =ase method: .(((.a=c()0
Hike the Stin& num%er$ CB is al'a"s 'atchin& ever" step "ou take and ever" move "ou make. Hike a
ha'k. Gou cannot call the unction a%c rom the %ase class as it does not carr" an" code alon& 'ith it
and has %een declared a%stract. Common sense prevails and CB does not allo' "ou to call a unction
that has no code.
a.cs
243884333.doc 134 od 221
class zzz
{
2blic static void Main()
{
yyy a + ne8 888();
??? b + ne8 888();
a.abc();b.abc();
}
}
class yyy
{
2blic virt2al void abc()
{
System.Console.WriteLine(Qyyy abcR);
}
}
abstract class ??? = yyy
{
2blic abstract ne8 void abc();
}
class 888 = ???
{
2blic override void abc()
{
System.Console.WriteLine(Q888 abcR);
}
}
:utput
((( a=c
@@@ a=c
a.a%c() 'ill irst peek into the class """. 3ere it inds unction a%c ta&&ed as virtual. 3o' man" times
have 'e repeated the a%ove lines? Countless times. CB 'ill then toddle over to class 888. 3ere it inds
to its disma" that the unction a%c is a%stract i.e. there is no code or a%c and also that it is a ne'
unction$ thus severin& all links 'ith the %ase class. Activit" stops and all hell %reaks loose and the
unction a%c rom """ &ets e8ecuted. !n the case o %.a%c()$ as the unction is ne'$ the links to the %ase
class are %roken$ 'e have no choice %ut to call the unction rom ''' as it sa"s override. <e cannot
replace the modiier ne' 'ith the ke"'ord override or unction a%c in a%stract class 888 .
Compiler 1rror
a.cs(&27): error C,0!5": .@@@0 does not implement inherited a=stract mem=er .///.a=c()0
! 'e replace the override ke"'ord 'ith ne' in class '''$ 'e 'ill &et an error as there is no code or
the unction a%c. 1emem%er the a%c o """ has nothin& to do at all 'ith that o 888 and '''.
)irtual unctions run slo'er than non virtual unctions and it is o%vious that an a%stract class cannot
%e sealed.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
sealed abstract class aaa
{
243884333.doc 13E od 221
2blic abstract void abc();
}
Compiler 1rror
a.cs(P$23)A error CS+E+2A :aaa: cannot %e %oth a%stract and sealed
1+
2roperties and !nde8ers
0roperties
0roperties are a natura! e1tension to )ie!ds. )er" e' pro&rammin& lan&ua&es support the notion o
a propert". ;nlike a 'ariab!e. a propert6 is not stored in a memor6 !ocation. It is made up o)
)unctions. -hus even thou&h a propert" and a ield share the same s"nta8 a propert" has the advanta&e
that code &ets called. <hen 'e initialiKe a varia%le$ no code in our class &ets called. <e are not a%le to
e8ecute an" code or a varia%le access or initialiKation at all. !n the case o a propert"$ 'e can e8ecute
tons o code. -his is one sin&ular reason or the popularit" o a product like )isual Basic 6 the use o
properties. .ne simple e8ample is settin& the value o a varia%le. ! it is throu&h a varia%le$ 'e have no
control over the value used. ! the same access is throu&h a propert"$ the pro&rammer has no inklin& o
'hether it is a propert" or a varia%le$ 'e can %uild ran&e checks to make sure that the varia%le does
not cross certain %ounds.
Hets start %" creatin& a simple propert". A propert" is a mem%er o a class. !t %ehaves like a varia%le
or the user.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
2blic class aa
{
2blic int Z {
}
}
Compiler 1rror
a.cs(92&): error C,0!"3: .aa.ff0 : propert( or inde/er must ha%e at least one accessor
<e have tried to create a propert" called 'hich is o t"pe int. <e &et an error %ecause a propert" is
used either on the let or the ri&ht o an e(ual to si&n. ! 'e had created a varia%le $ 'e 'ould like to
'rite a statement as && T , D. 3ere should return some value 'hich is o the data t"pe int.
a.cs
2blic class zzz
{
2blic static void Main()
{
243884333.doc 13L od 221
aa a + ne8 aa();
int ;; + a.Z - [;
System.Console.WriteLine(;;);
}
}
2blic class aa
{
2blic int Z {
;et
{
System.Console.WriteLine(Qin ;etR);
ret2rn '*;
}
}
}
:utput
in )et
&
A propert" should have at least one accessor$ in our case$ a &et as 'e 'ant to read the value o the
propert". -hus a. calls the &et accessor 'hich returns an int$ in this case 12. ! 'e did not have access
to the code o the class aa$ 'e 'ould have assumed to have %een a varia%le.
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
a.Z + '[;
System.Console.WriteLine(a.Z);
}
}
2blic class aa
{
2blic int Z {
;et
{
System.Console.WriteLine(Qin ;etR);
ret2rn '*;
}
set
{
System.Console.WriteLine(val2e);
}
}
}
:utput
&9
in )et
&
A varia%le can also %e used on the let6hand side o the e(ualto si&n. !n this case 'e are 'ritin& or
chan&in& the value o the varia%le. <e are passin& it some value. ! it is a propert"$ in our case$ a. T
1D 'ill call the accessor set. -he set accessor has a ree varia%le availa%le in it called value. !t &ets
created automaticall"$ 'e do not create this varia%le. !n our case$ this has the value 1D$ 'hich 'e are
243884333.doc 13P od 221
displa"in& in <riteHine. -hen to displa" the value o the propert" $ the &et needs to %e called a&ain.
-he &et al'a"s returns the same ans'er as the set does not store the value o the varia%le an"'here.
-o resolve this issue$ 'e do the ollo'in&.
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
a.Z + '[;
System.Console.WriteLine(a.Z);
}
}
2blic class aa
{
int 3';
2blic int Z {
;et
{
System.Console.WriteLine(Qin ;etR);
ret2rn 3';
}
set
{
System.Console.WriteLine(Qin set Q - val2e);
3' + val2e;
}
}
}
:utput
in set &9
in )et
&9
-o implement a propert" in real lie$ 'e create a pu%lic varia%le 'hich 'ill hold the value o the
propert". -his varia%le 1 'ill have the same data t"pe as the propert" i.e. an int in our case. !n the &et$
'e return 1 and in the set 'e initialiKe 1 to value. -his is the simplest case possi%le.
-he reason 'e use a propert" and not a varia%le is %ecause i 'e chan&e the value o a varia%leNield$
then code in our class is not a'are o the chan&e. Also 'e have no control over 'hat values the
varia%le 'ill contain. -he user can chan&e them to 'hatever heNshe likes and 'e cannot implement
ran&e checks on the varia%le. Also the user ma" 'ant to associate some action 'ith the chan&es in the
value o the varia%le. ;sin& a propert"$ readin& or 'ritin& to the varia%le also can %e monitored.
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
a.Z + '[;
System.Console.WriteLine(a.Z);
}
}
2blic class aa
{
243884333.doc 138 od 221
int 3';
2blic int Z {
;et
{
System.Console.WriteLine(Qin ;etR);
ret2rn 3';
}
}
}
Compiler 1rror
a.cs(A2&): error C,000: -ropert( or inde/er .aa.ff0 cannot =e assi)ned to X it is read onl(
Gou are allo'ed to declare a propert" readonl" %" omittin& the set accessor. /o one is no' allo'ed to
chan&e the value o the propert". !t no' %ehaves as a const or readonl" ield.
a.cs
2blic class zzz
{
2blic static void Main()
{
aa a + ne8 aa();
a.Z + '[;
}
}
2blic class aa
{
int 3';
2blic int Z {
set
{
System.Console.WriteLine(Qin set Q - val2e);
3' + val2e;
}
}
}
:utput
in set &9
-heoreticall"$ "ou can have a propert" 'hich is 'rite onl" i.e. onl" 'ith a set accessor. <ith set$ "ou
can chan&e the value o %ut it is o limited use %ecause "ou can never access the value o . A
propert" diers rom a ield %" endin& 'ith QR.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
2blic class aa
{
2blic int Z {
set
{
}
}
2blic int Z {
243884333.doc 13D od 221
;et
{
}
}
}
Compiler 1rror
a.cs(&2&): error C,0&0: 6he class .aa0 alread( contains a definition for .ff0
Gou cannot create a propert" in 2 separate %its and pieces. !t has to %e in one 'hole. -his is part o the
s"nta8. -he a%ove creates t'o properties$ %oth called $ the irst one %ein& 'rite onl"$ the second$ read
onl". -he compiler tells "ou that "ou cannot create t'o properties %" the same name.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
2blic class aa
{
rivate int Z;
2blic int Z {
;et {
}
set {
}
}
}
Compiler 1rror
a.cs(&02&): error C,0&0: 6he class .aa0 alread( contains a definition for .ff0
Gou o%viousl" cannot have a propert" and varia%le 'ith the same name. -he compiler 'ould not kno'
'hether to invoke the propert" or the ield. -he" %oth are stored in the same namespace.
a.cs
class zzz
{
2blic static void Main()
{
yyy.i + *(;
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
2blic static int i
{
;et {
System.Console.WriteLine(Q;etR);
ret2rn '(;
}
set {
System.Console.WriteLine(Qset Q - val2e);
}
}
}
243884333.doc 14+ od 221
:utput
set 0
)et
&0
-he rules o static appl" to properties also. Hike varia%le 'e access them usin& the class and not the
instance. 0ver"thin& that 'e have learned a%out static in the past applies to properties also.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.i + '((;
System.Console.WriteLine(a.i);
}
}
abstract class ???
{
2blic abstract int i
{
;et ;
set ;
}
}
class yyy = ???
{
2blic override int i {
;et
{
System.Console.WriteLine(Q;etR);
ret2rn '(;
}
set
{
System.Console.WriteLine(Qset Q - val2e);
}
}
}
:utput
set &00
)et
&0
-he a%stract propert" i in class 888 carries no code at all. -he &et and set accessors are simpl"
represented %" a semicolon. !n the derived class$ 'e must implement %oth the &et and the set
accessors. ! 'e do not use the override ke"'ord$ it is ne'. <e hope "ou have inall" understood ne'
and override.
a.cs
class zzz
{
2blic static void Main()
{
}
}
243884333.doc 141 od 221
abstract class ???
{
2blic abstract int i
{
;et ;
}
}
class yyy = ???
{
2blic override int i {
;et
{
}
set
{
}
}
}
Compiler 1rror
a.cs(02&): error C,0!"A: .(((.i.set0: cannot o%erride =ecause .///.i0 does not ha%e an
o%errida=le set accessor
!n class 888$ the a%stract propert" has onl" a &et accessor. !n the derived class 'e are implementin&
%oth the &et and the set. -he ori&inal never ever had a set. -his is unaccepta%le to the compiler. -hus
'e have no choice %ut to implement onl" the accessors that are present in the ori&inal. A &et accessor
can %e vie'ed as a method 'hich returns a value %ut accepts no parameters.
a.cs
class yyy
{
2blic void i {
}
}
Compiler 1rror
a.cs(52&5): error C,0!"7: .i0 : propert( or inde/er cannot ha%e %oid t(pe
!t makes no sense or an accessor to have a void t"pe as a varia%le cannot %e o t"pe void. )oid
literall" means 4! do not kno' the t"pe7 or no t"pe at all.
a.cs
class yyy
{
2blic int i {
set
{
ret2rn '(;
}
}
}
Compiler 1rror
a.cs(A2): error C,0&7: ,ince .(((.i.set0 returns %oid2 a return De(@ord must not =e follo@ed
=( an o=Eect e/pression
243884333.doc 142 od 221
A set accessor can %e vie'ed as unction 'hich returns void %ut accepts one parameter 'hich stands
or the value o the propert". -hus a set cannot return a value. ! 'e remove the 1+$ 'e 'ill not &et an
error.
a.cs
class zzz
{
2blic static void Main()
{
}
2blic int i {
set
{
val2e + *(;
}
}
}
-he reserved varia%le value in the set can %e chan&ed at 'ill. -hou&h$ understandin& 'h" an"one
'ould 'ant to do such dum% stu is %e"ond us.
a.cs
class zzz
{
2blic static void Main()
{
}
2blic int i {
set
{
int val2e;
}
}
}
Compiler 1rror
a.cs(92A): error C,0&5A: + local %aria=le named .%alue0 cannot =e declared in this scope
=ecause it @ould )i%e a different meanin) to .%alue02 @hich is alread( used in a .parent or
current0 scope to denote somethin) else
<e cannot ho'ever create a varia%le value as it 'ill clash 'ith the varia%le value 'hich is alread"
present %" deault in the set.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.i + '(;
??? b + ne8 ???();
((yyy)b).i + *(;
b.i + '(;
}
}
class yyy
{
2blic int i {
set {
243884333.doc 143 od 221
}
}
}
class ??? = yyy
{
2blic int i {
;et {
ret2rn '(;
}
} }
Compiler 1rror
a.cs(92&): error C,000: -ropert( or inde/er .///.i0 cannot =e assi)ned to X it is read onl(
!n the class """$ the propert" i has onl" the set accessor. !n the class 888 'hich derives rom """$ 'e
have implemented onl" the &et accessor. -he propert" i in class 888 hides the i o """. -he" do not add
up. <hat 'e are tr"in& to sa" is that %oth these properties are independent o each other. <hat 'e had
thou&ht CB 'ould have done is$ taken the set rom one class and added it to the second. 3o'ever$ that
does not make sense. !t treats them independentl". ! 'e 'ant to use the propert" o the class """$ then
'e need to e8plicitl" cast it as 'e have done or %. -hus the propert" i o class """ &ets hidden %ut can
%e accessed.
A propert" is not necessaril" slo'er than a varia%le. A varia%le access normall" initialiKes some
memor"$ 'hereas a propert" e8ecutes a method. -his is not necessaril" slo'er as at times$ CB 'ill
re'rite "our propert" methods to memor" accesses. -his is called inlinin& o code. 08cept or minor
dierences$ all that 'e mentioned a%out virtual$ a%stract and ne' appl" also to a propert". -he
dierence is$ i the ori&inal propert" has a &et and a set$ the derived class 'ill onl" implement a set or
a &et.
Inde1ers
An inde8er lets us access mem%ers o a class as i it 'ere an arra".
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
aD'E + '(;
}
}
2blic class yyy {
}
Compiler 1rror
a.cs(A2&): error C,00&: Cannot appl( inde/in) @ith #' to an e/pression of t(pe .(((0
<e have created an o%*ect a that looks like """. -he o%*ect a$ in no sense o the 'ord is an arra". <e
are assumin& that a is an arra" and 'e7ve used the arra" s"nta8 aWX$ hence it &ives us an error.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
aD'E + '(;
}
243884333.doc 144 od 221
}
2blic class yyy
{
2blic int t9isDint iE
{
set {
System.Console.WriteLine(Qin ;et Q - val2e - Q Q - i);
}
}
}
:utput
in )et &0 &
<e7ve added a e' lines to have the arra" notation 'ork 'ith an o%*ect that looks like """. -o
implement inde8ers$ 'e need to create a special propert" called this. -his is a reserved 'ord. As o
no'$ 'e have a parameter i (an int) in the s(uare %rackets. <hen 'e did properties earlier$'e learnt
that a set &ets called 'henever 'e 'ant to initialiKe or set a varia%le. <ithin the set accessor 'e have
a special varia%le called value 'hich stores the value passed to the set$ in this case 1+. -he varia%le i
'ill hold the value 1 as the arra" parameter is 1.
-his is ho' 'e implement arra"s 'hen there are none.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
System.Console.WriteLine(aD'E);
}
}
2blic class yyy
{
2blic int t9isDint iE
{
set
{
System.Console.WriteLine(Qin ;et Q - val2e - Q Q - i);
}
;et
{
System.Console.WriteLine(Qin set Q - i);
ret2rn *,;
}
}
}
:utput
in set &
5
-he rules %indin& properties are applica%e to inde8ers too. <hen "ou 'ant to read the value o aW1X$
the &et &ets called. -he ma*or dierence %et'een properties and inde8ers is that 'hen "ou implement
the code or inde8ers "ou have to understand that the &et and set &et called 'ith a varia%le 'hich is the
arra" parameter value. -he code 'ill have to understand arra" simulation.
a.cs
243884333.doc 14E od 221
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
aDQ9iRE + ,(;
System.Console.WriteLine(aDQ9iRE);
}
}
2blic class yyy
{
2blic int z;
2blic int t9isDstrin; iE
{
set
{
System.Console.WriteLine(Qin ;et Q - val2e - Q Q - i);
z + val2e;
}
;et
{
System.Console.WriteLine(Qin set Q - i);
ret2rn z;
}
}
}
:utput
>n )et 50 hi
>n set hi
50
-he this propert" has a return value$ in this case$ an int. Also the WX %rackets can contain data t"pes
other than an int. !n this case a strin&. -he strin& i has a value hi as that is 'hat 'e passed in the arra"
%rackets. Gou can have t'o this7s in "our class. Gou have to decide 'hat data t"pe to use in the arra"
%rackets. An inde8er is ver" useul 'hen "ou have a data%ase o%*ect and "ou 'ant to access the data in
the ields usin& a notation W^ieldname_X
!nde8ers ollo' the same concepts o virtual$ ne'$ override etc.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
aD'E + '(;
aDQoneRE + '(;
aDQ9iR)*E + ,(;
}
}
class yyy
{
2blic int t9is D int iE
{
set
{
System.Console.WriteLine(Qone int Q- i - Q Q - val2e);
}
}
243884333.doc 14L od 221
2blic int t9is D strin; iE
{
set
{
System.Console.WriteLine(Qone strin; Q- i - Q Q - val2e);
}
}
2blic int t9is D strin; i) int 4E
{
set
{
System.Console.WriteLine(Qone strin; and int Q- i - Q Q - 4 - Q Q - val2e);
}
}
}
:utput
one int & &0
one strin) one &0
one strin) and int hi 50
-he si&nature o an inde8er is the num%er and t"pes o ormal parameters. -he return value and the
names o the parameters do not contri%ute to the inde8ers si&nature. -hus 'e have overloaded the
inde8ers to take an int$ strin& or a strin& int com%ination. 0ach time a dierent unction &ets called.
-he point to understand is that all the inde8ers have to return the same data t"pe$ in our case int. -he
same rules that appl" to unction overloadin& appl" here also. #unctions cannot dier onl" %" return
values. <e are sure that or inde8ers in the ne8t version$ CB shouldNmust make an e8ception.
A propert" is identiied %" its name$ an inde8er %" its si&nature. -here is no concept o propert"
overloadin& in CB.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class yyy
{
2blic static int t9is D int iE
{
set
{
}
}
}
Compiler 1rror
a.cs(92&9): error C,0&0A: 6he modifier .static0 is not %alid for this item
A propert" can %e %oth an instance mem%er 'hich is the deault or static. An inde8er unortunatel" can
onl" %e an instance mem%er and not static. @od alone kno's 'h" this discrimination a&ainst inde8ers.
.nce a&ain no rational reason or the a%ove error. .%viousl" "ou cannot create a varia%le 'ith the
same name as that o the parameter passed in the inde8er.
a.cs
243884333.doc 14P od 221
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
aD*E + *(;
System.Console.WriteLine(aD*E);
}
}
class yyy
{
2blic virt2al int t9is D int iE
{
;et
{
System.Console.WriteLine(Qyyy ;et Q - i);
ret2rn *(;
}
set
{
System.Console.WriteLine(Qyyy set Q - val2e - Q Q - i);
}
}
}
class ??? = yyy
{
2blic override int t9is D int iE
{
;et
{
int + baseDiE;
System.Console.WriteLine(Q??? ;et Q - i - Q Q - );
ret2rn *((;
}
set
{
System.Console.WriteLine(Q??? set Q - val2e - Q Q - i);
baseDiE + val2e;
}
}
}
:utput
/// set 0
((( set 0
((( )et
/// )et 0
00
-he a%ove e8ample deals 'ith callin& the inde8ers o the %ase class. At times 'hen 'e are overridin&
code in the derived class$ 'e 'ould like to call the ori&inal inde8er in the %ase class irst. -he irst rule
that 'e have to adhere to is that the inde8er in the %ase class must %e declared virtual. !n the derived
class$ 'e are no' declarin& it 'ith the modiier override. Same rules as a%ove. !n the set accessor$ 'e
have to call the ori&inal as %aseWiX$ 'here i is the inde8 to the inde8er. Also 'e need to pass it the value
to initialiKe itsel. -his is stored in the varia%le value. -his aW2X in 9ain &ets replaced %" %aseW2X in the
set. !n &et the reverse takes place. 3ere 'e need to place %aseWiX on the ri&ht o the e(ualto si&n$ the
ori&inal &et 'ill return a value$ in this case 2+$ 'hich 'e are storin& in a varia%le p. <hat 'e do 'ith p
as 'ell as the value rom the &et is our %usiness.
243884333.doc 148 od 221
a.cs
class yyy
{
2blic int t9is D byte i ) strin; 4E
{
;et
{
ret2rn '(;
}
set
{
}
}
int ;etV"tem(byte i)strin; 4)
{
ret2rn *(
}
void setV"tem(byte i)strin; 4 ) int val2e)
{
}
}
Compiler 1rror
a.cs(!2&): error C,0&&&: Class .(((0 alread( defines a mem=er called .)etW>tem0 @ith the same
parameter t(pes
a.cs(92&): error C,0&&&: Class .(((0 alread( defines a mem=er called .setW>tem0 @ith the same
parameter t(pes
Hike a propert"$ an inde8er also &ets a name chan&e. ! people can &et their %odies pierced
then 'h" cannot a inde8er &et converted to a series o unctions startin& 'ith &et? #or a &et$
the parameters are the same as 'e pass to an inde8er. !t has a return value and the t"pe o the
inde8er. Also the set has one more added parameter and that is the ree varia%le value.
11
!nteraces and Structures
Constructors 4e'isited
A constructor is used to initialiKe the instance o a class as e8plained earlier.
a.cs
2blic class zzz
{
2blic static void Main()
{
System.Console.WriteLine("in main");
bb a + ne8 bb();
bb b + ne8 bb('();
}
}
2blic class aa
{
2blic aa()
243884333.doc 14D od 221
{
System.Console.WriteLine("in const aa");
}
2blic aa(int i)
{
System.Console.WriteLine("in const aa" - i);
}
}
2blic class bb = aa
{
2blic bb()
{
System.Console.WriteLine("in const bb");
}
2blic bb(int i)
{
System.Console.WriteLine("in const bb" - i);
}
}
:utput
in main
in const aa
in const ==
in const aa
in const ==&0
Class aa is the %ase class. !t consists o t'o constructors. .ne that takes no parameters and the other
that takes an int as a parameter. Class %% is derived rom class aa$ i.e. aa is the %ase class$ %% the
derived class. <hen 'e create an o%*ect like %%$ the compiler does not e8ecute the code or the
constructor %ut instead asks the constructor 'hich constructor o the %ase class to e8ecute irst. As 'e
haven:t stated this$ %" deault$ the constructor 'ith no parameters &et e8ecuted. 1emem%er it is the
%ase class constructor 'hich &ets e8ecuted irst and the derived class constructor speciies 'hich %ase
class constructor to call irst. !n the second case$ even thou&h 'e are callin& the constructor 'ith a
parameter$ the constructor 'ith no parameters in the %ase class &ets called and not the one 'ith one int
as a parameter.
a.cs
2blic class zzz
{
2blic static void Main()
{
System.Console.WriteLine("in main");
bb a + ne8 bb();
bb b + ne8 bb('();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("in const aa");
}
2blic aa(int i)
{
243884333.doc 1E+ od 221
System.Console.WriteLine("in const aa" - i);
}
}
2blic class bb = aa
{
2blic bb() = base()
{
System.Console.WriteLine("in const bb");
}
2blic bb(int i) = base(i)
{
System.Console.WriteLine("in const bb" - i);
}
}
:utput
in main
in const aa
in const ==
in const aa&0
in const ==&0
! 'e do not speci" 'hich constructor o the %ase class to call$ CB %" deault calls the constructor 'ith
no parameters. <hich means that CB re'rites our code . <hen 'e 'rite %%()$ it &ets re'ritten as %%() A
%ase(). Base is a reserved 'ord. !t means call the constructor o the %ase class 'ith no parameters. #or
the second constructor$ %%(int i)$ the line &ets re'ritten to %%(int i) A %ase(). <e no' 'ant to call the
constructor 'ith one int and hence 'e 'rite %%(int i) A %ase(i). -hat is 'h" the constructor 'ith one int
&ets called. <e have the option to decide 'hich constructor o the %ase class 'e 'ould like to call.
a.cs
2blic class zzz
{
2blic static void Main()
{
System.Console.WriteLine("in main");
bb a + ne8 bb();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("in const aa");
}
2blic aa(int i)
{
System.Console.WriteLine("in const aa" - i);
}
}
2blic class bb = aa
{
2blic bb() = t9is(*()
{
System.Console.WriteLine("in const bb");
}
2blic bb(int i) = base(i)
{
System.Console.WriteLine("in const bb" - i); } }
:utput
243884333.doc 1E1 od 221
in main
in const aa0
in const ==0
in const ==
A constructor &ets called at the time o creation o the o%*ect. At the line$ ne' %%()$ the compiler asks
the constructor o %% as to 'hich constructor o the %ase class aa to call. 3ere he 'as told that the
ans'er lies 'ith this(2+). this$ like %ase$ is a reserved 'ord. !t means call a constructor o the same
class and not the %ase class. -hereore the compiler no' asks the one constructor o the derived class
%% 'hich constructor o the %ase class to call. %%(int i) A %ase(i) tells the compiler to e8ecute the one int
constructor o aa. -his is the irst constructor that &ets called. -hen the one int constructor o %% &ets
called and inall" the one 'ho started it all$ the no parameter constructor o %%. -hus$ t'o derived
class constructors &et called instead o one.
a.cs
2blic class zzz
{
2blic static void Main()
{
System.Console.WriteLine("in main");
aa a + ne8 aa();
}
}
2blic class aa
{
rivate aa()
{
}
}
Compiler 1rror
a.cs(A23): error C,0&: 7aa.aa()7 is inaccessi=le due to its protection le%el
<hen "ou create a constructor 'hich is private$ "ou cannot create an o%*ect that looks like aa. -hus aa
should onl" contain static mem%ers.
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
2blic class aa
{
rivate aa()
{
}
}
2blic class bb = aa
{
}
Compiler 1rror
a.cs(&52&"): error C,0&: 7aa.aa()7 is inaccessi=le due to its protection le%el
/or can an" class derive rom aa. -hus no one can instantiate an o%*ect that looks like aa or derive
rom it as the constructor has %een made private.
243884333.doc 1E2 od 221
a.cs
2blic class zzz
{
2blic static void Main()
{
System.Console.WriteLine(aa.i);
}
}
2blic class aa
{
rivate aa()
{
}
static 2blic int i + *(;
}
:utput
0
Gou can ho'ever use all the static varia%les in aa
a.cs
2blic class zzz
{
2blic static void Main()
{
}
}
class yyy
{
2blic yyy()
{
}
}
class ??? = yyy
{
2blic int i;
???() = base( t9is.i)
{
}
}
Compiler 1rror
a.cs(&A2&!): error C,007: Ve(@ord this is not a%aila=le in the current conte/t
Base is called a constructor initialiKer. <hen %ase &ets called$ the instance or the o%*ect has not "et
%een created. 0r&o$ this is not availa%le here as this reers to the current o%*ect. !n the constructor$
ho'ever$ this can %e reel" used.
-he values o varia%les in a class are initialiKed to their deault values as per their data t"pes %eore
the constructor &ets called. -hus$ in the constructor the" have their deault values as sho'n %elo'.
a.cs
2blic class zzz
{
2blic static void Main()
{
243884333.doc 1E3 od 221
yyy a + ne8 yyy();
}
}
class yyy
{
2blic int i;
2blic bool 4;
2blic yyy()
{
System.Console.WriteLine(i-" " - 4);
}
}
:utput
0 Balse
3ere as %eore$ the irst line o code in the constructor &ets e8ecuted.
a.cs
2blic class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
}
}
class yyy
{
2blic int i + '(;
2blic yyy(int 4)
{
System.Console.WriteLine(i);
i + 4;
}
}
class ??? = yyy
{
2blic ???() = base('(()
{
System.Console.WriteLine(base.i);
}
}
:utput
&0
&00
Callin& the %ase class constructor is like insertin& all the code o the one int constructor i.e. """(int *)$
in the constructor o class 888. <e are also allo'ed to access mem%ers o the %ase class ater the
constructor &ets called. Also$ irst the varia%le i &ets initialiKed to 1+ or the deault value o int. -hen
'e chan&e it to 1++ and in the constructor o 888$ 'e 'ill see a value o 1++.
a.cs
2blic class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
}
243884333.doc 1E4 od 221
}
class yyy
{
2blic yyy()
{
abc();
}
2blic virt2al void abc()
{
}
}
class ??? = yyy
{
2blic int ? + '(;
2blic ???()
{
System.Console.WriteLine(?);
? + '((;
System.Console.WriteLine(?);
}
2blic override void abc()
{
System.Console.WriteLine(?);
}
}
:utput
&0
&0
&00
<e have alread" conessed a million times in the past that 'e have copied ideas rom an"one and
ever"one$ speciall" rom the documentation. !n this speciic case$ 'e 'anted to demonstrate that irst
the varia%les are initialiKed. -hus in class 888$ the int 8 is initialiKed to 1+. -hen the %ase class
constructor o """ &ets called. -he value o 8 in class """ should %e 1+. But 'hat &uarantee can 'e
&ive "ou as 'e are not a%le to print the value o 8 in an o%*ect o a class derived rom the %ase class.
)er" simple. <e call a virtual unction a%c rom class """ and override it in class 888. -he a%c o class
888 prints the value o 8 as the" %elon& to the same class and the output is 1+. )iola and thank "ou 9r.
>ocumentation or the a%ove thou&ht and man" more such ideas. .nce all code in the """ constructor
is e8ecuted$ the irst line in 888 constructor 'ill &et e8ecuted 'hich 'ill print the value o 8 as 1+. 8 is
then initialiKed to 1++$ hence 'e see 1++ as the ne' value o 8$ displa"ed on the screen.
a.cs
2blic class zzz
{
static zzz()
{
System.Console.WriteLine("zzz");
}
2blic static void Main()
{
System.Console.WriteLine("main");
ne8 aa();
}
}
2blic class aa
{
2blic aa()
{
243884333.doc 1EE od 221
System.Console.WriteLine("aa");
}
static aa()
{
System.Console.WriteLine("static aa");
}
}
:utput
999
main
static aa
aa
and i 'e comment ne' aa() then the resultin& output reads as ollo's.
:utput
999
main
A static constructor &ets called %eore an" other constructors.
a.cs
2blic class zzz
{
static zzz()
{
System.Console.WriteLine("zzz");
}
2blic static void Main()
{
System.Console.WriteLine("main");
aa.a();
}
}
2blic class aa
{
2blic aa()
{
System.Console.WriteLine("aa");
}
2blic static void a()
{
}
static aa()
{
System.Console.WriteLine("static aa");
}
}
:utput
999
main
static aa
! "ou tr" to access an" static mem%er o a class or 'henever "ou instantiate an o%*ect$ the static
constructor &ets called. A constructor is not inherited %" the derived class.
243884333.doc 1EL od 221
A class is loaded in memor" %eore an" instance o the class is created or its static mem%ers accessed.
A class can onl" %e loaded once and that too %eore its derived class is loaded. -he static constructor is
called at the time o loadin& the class. Hike other constructors$ a static constructor cannot %e e8plicitl"
called.
a.cs
2blic class zzz
{
2blic static void Main()
{
???.!r();
yyy.abc();
}
}
class yyy {
static yyy()
{
System.Console.WriteLine("static yyy");
}
2blic static void abc()
{
System.Console.WriteLine("abc yyy");
}
}
class ??? {
static ???()
{
System.Console.WriteLine("static ???");
}
2blic static void !r()
{
System.Console.WriteLine("!r ???");
}
}
:utput
static ///
pHr ///
static (((
a=c (((
>o not %elieve the a%ove results as i "ou run them on "our machine$ "our milea&e ma" 'ar". -his is
%ecause CB does mandate the order o loadin& o classes and thus the order o e8ecution o the static
constructors. .n "our machine i the """ constructor &ets e8ecuted irst$ do not panic. Blame it on
"our destin".
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy.abc();
???.!r();
}
}
class ???
{
static ???()
{
System.Console.WriteLine("static ???");
243884333.doc 1EP od 221
}
2blic static void !r()
{
System.Console.WriteLine("!r ???");
}
}
class yyy = ???
{
static yyy()
{
System.Console.WriteLine("static yyy");
}
2blic static void abc()
{
System.Console.WriteLine("abc yyy");
}
}
:utput
static (((
a=c (((
static ///
pHr ///
<e have made onl" one small chan&e in the a%ove pro&ram. <e have derived the class """ rom 888.
Since the unctions in each class are marked static$ the pro&ram %ehaves in the same manner as
%eore.-he a%ove order o calls remains the same. ! an o%*ect o the t"pe is created$ then the output
'ill chan&e. -he reason %ein& that %eore the o%*ect o t"pe """ is created$ 888 must %e loaded. 3ence
the constructors 'ill %e called irst.
a.cs
2blic class zzz
{
2blic static int ? + yyy.y - *;
static zzz()
{
System.Console.WriteLine("static zzz " - zzz.? - " " - yyy.y);
? + .((;
yyy.y + 5((;
System.Console.WriteLine("static zzz " - zzz.? - " " - yyy.y);
}
2blic static void Main()
{
System.Console.WriteLine("main "- zzz.? - " " - yyy.y);
}
}
class yyy
{
static yyy()
{
System.Console.WriteLine("static yyy " - zzz.? - " " - yyy.y);
y + '(;
zzz.? + *((;
System.Console.WriteLine("static yyy " - zzz.? - " " - yyy.y);
}
2blic static int y + zzz.? - ,; }
:utput
static ((( 0 5
243884333.doc 1E8 od 221
static ((( 00 &0
static 999 & &0
static 999 !00 A00
main !00 A00
>iicult code to understand and ollo'. CB irst tries to load class KKK in memor" as it contains the
unction 9ain. ;nortunatel" it realiKes that it has to irst initialiKe the varia%le 8 %eore callin& the
static constructor o KKK. !t irst initialiKes 8 to +. /o' note that this initialiKation o 8 to Kero is
e8tremel" si&niicant or our understandin&. -o &et the ne' value o 8$ CB no' needs the value o the
varia%le " rom the class """. Beore it can call the static constructor o """ it must initialiKe the
varia%le ". !t makes sure that ":s value is irst set to Kero. !t then computes the value o KKK.8 'hich is
Kero as stated a%ove. <e are "et let han&in& in class KKK at the line 8 T . As KKK.8 is Kero$ the value o
" is + , 3 i.e. 3. -his completes the initialiKation o all the varia%les in the class. All this happens irst.
-hus the static constructor o class """ sho's the value o the varia%le 8 as + and that o varia%le " as
3.
But hold on$ the un is "et to %e&in. !n the static constructor$ 'e no' initialiKe " to 1+ and the 8 o KKK
to 2++. -he ne8t <riteHine conirms that our initialiKations actuall" 'ere carried out. -hen 'e &o %ack
to class KKK. 3ere 'e come %ack to the initialiKation o the static varia%le 8. As """." is no' 1+ since
'e chan&ed it in the static constructor o """$ the value o 8 is 1+ , 2 i.e. 12. -his overrides the value
o 8 'hich 'e chan&ed to 2++ in the static constructor """. /o' CB calls the static constructor o KKK
as it has inished all the varia%le initialiKations. -hus the irst <riteHine displa"s 12 and 1+. <e are
no' chan&in& %oth 8 and " and the" displa" the same values in the constructor and in 9ain.
a.cs
2blic class zzz
{
2blic static int ? + yyy.y - *;
static zzz()
{
System.Console.WriteLine("static zzz " - zzz.? - " " - yyy.y);
? + .((;
yyy.y + 5((;
System.Console.WriteLine("static zzz " - zzz.? - " " - yyy.y);
}
}
class yyy
{
static yyy()
{
System.Console.WriteLine("static yyy " - zzz.? - " " - yyy.y);
y + '(;
zzz.? + *((;
System.Console.WriteLine("static yyy " - zzz.? - " " - yyy.y);
}
2blic static int y + zzz.? - ,;
2blic static void Main()
{
System.Console.WriteLine("main "- zzz.? - " " - yyy.y);
}
}
:utput
static 999 0
static 999 !00 A00
static ((( !00 !05
static ((( 00 &0
main 00 &0
243884333.doc 1ED od 221
-he a%ove pro&ram adds a small t'ist. !t %o'ls 'hat in cricket parlance is called a &oo&l". <e simpl"
%rin& 9ain rom the class KKK to the class """. /o' CB as usual irst starts at the class containin&
9ain 'hich no' happens to %e """ and not KKK. 3ere it has to irst initialiKe all the varia%les in class
""". <e have onl" one. !t starts %" settin& " to Kero and runs to the class KKK to etch the value o 8. 8
no' %ecome + , 2 i.e. 2. -hen in the static constructor$ 'e are displa"in& the relevant values o 8 and
". !n the static constructor o class KKK$ 'e are chan&in& 8 and " to E++ and L++ respectivel" and
displa"in& the values. <hen 'e move %ack to class """$ ho'ever$ " &ets a ne' value o E+3 as 8 is
E++. " loses its value o L++ that 'as initialiKed in KKK$ hence "ou see E++ and E+3. -he rest remains
the same as e8plained in the earlier e8ample.
Inter)aces
An interace is simpl" a collection o unction protot"pes. Hike 'e derive a class rom another$ so also
'e could derive rom an interace.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace ddd
{
void a'();
void a*();
}
class yyy = ddd
{
}
Compiler 1rror
a.cs(&27): error C,0!5!: 7(((7 does not implement interface mem=er 7ddd.a&()7
a.cs(&27): error C,0!5!: 7(((7 does not implement interface mem=er 7ddd.a()7
<e have *ust created an interace called ddd %" usin& a ne' ke"'ord interace in place o a class. .ur
interace ddd has t'o unction protot"pes$ a1 and a2. <e can derive rom our interace ddd like 'e
derived rom a class. -he dierence is that an interace has no code$ onl" unction protot"pes.
<henever 'e derive rom an interace$ 'e have to implement the code or %od" o the unction. A class
&ives "ou lots o ree code$ an interace does not. -he error is &enerated as 'e have not &iven the code
or a1 and a2 in """
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.a'();
ddd d + ne8 yyy();
d.a*();
}
}
inter3ace ddd
{
void a'();
243884333.doc 1L+ od 221
void a*();
}
class yyy = ddd
{
2blic void a'()
{
System.Console.WriteLine("yyy a'");
}
2blic void a*() {
System.Console.WriteLine("yyy a*");
}
}
:utput
((( a&
((( a
<e &et no errors %ecause 'e have no' implemented the code o a1 and a2. Hooks 'ise 'e do no
kno' 'hether ddd is a class or an interace as the s"nta8 at the time o derivation is the same. d is an
o%*ect that looks like an interace 'hich is s"ntacticall" correct. d can %e e(uated to a """ as a """ is a
""" , a ddd. <e can$ %" onl" usin& d$ call mem%ers o a ddd.
a.cs
class zzz
{
2blic static void Main()
{
aaa a ;
a + ne8 aaa();
}
}
inter3ace aaa
{
}
Compiler 1rror
a.cs(A2!): error C,0&"": Cannot create an instance of the a=stract class or interface 7aaa7
0ven thou&h an interace aaa is empt"$ 'e cannot 'rite the ke"'ord ne' in ront o it. An interace
contains no code and thus cannot %e instantiated. 3o'ever 'e are allo'ed to declare o%*ects that look
like an interace. -hereore$ in this case$ the line aaa a$ does not la& an error.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void a'()
{
}
}
Compiler 1rror
a.cs(92A): error C,0!5&: 7aaa.a&()7: interface mem=ers cannot ha%e a definition
243884333.doc 1L1 od 221
1eiteratin&$ an interace can onl" contain unction protot"pes$ no code at all. -he unctions cannot
have a deinition.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class ???
{
}
class vvv
{
}
class yyy = ???)vvv
{
}
Compiler 1rror
a.cs(&52&7): error C,0!7: 7%%%7 : t(pe in interface list is not an interface
CB does not support multiple inheritance. <e can derive rom a sin&le class onl" at one point in time.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
ddd d + ne8 yyy();
d.a'(); d.a*();
a.a'();
a.a*();
}
}
inter3ace ddd
{
void a'();
void a*();
}
class yyy = ddd
{
2blic void ddd.a'()
{
System.Console.WriteLine("a'");
}
2blic void a*()
{
System.Console.WriteLine("a*");
}
}
Compiler 1rror
a.cs(&92&5): error C,0&0A: 6he modifier 7pu=lic7 is not %alid for this item
Gou are not allo'ed to use the modiier pu%lic or a unction 'hich has (ualiied its name 'ith that o
the interace.
243884333.doc 1L2 od 221
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
2blic void a'();
}
Compiler 1rror
a.cs(92&5): error C,0&0A: 6he modifier 7pu=lic7 is not %alid for this item
!nterace mem%ers are pu%lic %" deault. -he access modiiers are not allo'ed here. All the other
access modiier rules remain the same as that rom classes. -he rules in classes stated that the %ase
class must %e at least as accessi%le as the derived class. 1eplace the 'ord class 'ith interace and "ou
'ill not %e sorr".
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
ddd d + ne8 yyy();
d.a'(); d.a*();
a.a'();
a.a*();
}
}
inter3ace ddd
{
void a'();
void a*();
}
class yyy = ddd
{
void ddd.a'()
{
System.Console.WriteLine("a'");
}
2blic void a*()
{
System.Console.WriteLine("a*");
}
}
Compiler 1rror
a.cs(32&): error C,0&&7: 7(((7 does not contain a definition for 7a&7
-he reason 'e &et an error is %ecause 'e created the unction a1 in """ as ddd.a1 and not a1. B"
doin& this$ 'e 'ere tellin& CB that onl" o%*ects that look like ddd are allo'ed access to a1. 0ven an
o%*ect that looks like """ is not allo'ed to access a1. Comment out line num%er 8 i.e. a.a1 and all
'orks ine as ollo's
243884333.doc 1L3 od 221
:utput
a&
a
a
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
ddd d + ne8 yyy();
eee e + ne8 yyy();
a.a'(); a.a*();
d.a'();
e.a*();
}
}
inter3ace ddd
{
void a'();
}
inter3ace eee
{
void a*();
}
class yyy = ddd ) eee
{
2blic void a'()
{
System.Console.WriteLine("a'");
}
2blic void a*()
{
System.Console.WriteLine("a*");
}
}
:utput
a&
a
a&
a
3ere 'e are doin& somethin& that *ust cannot %e done 'ith classes. <e are derivin& rom t'o
interaces ddd and eee at the same time. 0ach has one unction protot"pe a1 and a2 respectivel". ;sin&
a 'hich looks like """ 'e can call %oth a1 and a2 %ut 'ith d that looks like ddd 'e can onl" call a1.
Similarl"$ 'ith e onl" a2 can %e called.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
ddd d + ne8 yyy();
eee e + ne8 yyy();
a.a'();
d.a'();
243884333.doc 1L4 od 221
e.a'();
}
}
inter3ace ddd
{
void a'();
}
inter3ace eee
{
void a'();
}
class yyy = ddd ) eee
{
2blic void a'()
{
System.Console.WriteLine("a'");
}
}
:utput
a&
a&
a&
-he t'o interaces share the same unction name a1. <e do not &et an error %ut "et thin&s do not seem
ri&ht. Both d and e call the same a1 and there is onl" one implementation o the unction a1. <e
'ould like to have t'o a1:s %ut 'e cannot have the same unction deined t'ice in a class.
a.cs
class zzz
{
2blic static void Main()
{
ddd d + ne8 yyy();
eee e + ne8 yyy();
d.a'();
e.a'();
}
}
inter3ace ddd
{
void a'();
}
inter3ace eee
{
void a'();
}
class yyy = ddd ) eee
{
void ddd.a'()
{
System.Console.WriteLine("ddd a'");
}
void eee.a'()
{
System.Console.WriteLine("eee a'");
}
}
243884333.doc 1LE od 221
:utput
ddd a&
eee a&
<e did 'hat 'e had e8plained earlier. <e preaced the name o the unction 'ith the name o the
interace. -hen 'e removed the modiier pu%lic and the o%*ect a 'hich looked like """. /o' each
interace has its o'n cop" o a1 to %e called. ddd.a1 is called the e8plicit interace mem%er name.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.a'();
}
}
inter3ace ddd
{
void a'();
}
inter3ace eee
{
void a'();
}
class yyy = ddd ) eee
{
void ddd.a'()
{
System.Console.WriteLine("ddd a'");
}
void eee.a'()
{
System.Console.WriteLine("eee a'");
}
}
Compiler 1rror
a.cs(A2&): error C,0&&7: 7(((7 does not contain a definition for 7a&7
-he reason 'e removed a 'as that once 'e have an e8plicit interace mem%er$ 'e cannot access it
throu&h the class$ it is done onl" throu&h the interace. -his make a lot o sense as there are t'o
unctions o the same name$ and CB does not kno' 'hich one it should call. B" preacin& the
unctions 'ith the names o the interace$ 'e are makin& them part o the interace and not the class.
!n a sense the" are private to the class. As there is no unction %" the name o a1 in class """$ 'e see
the a%ove error.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace ddd
{
void a'();
}
243884333.doc 1LL od 221
inter3ace eee
{
void a'();
}
class yyy = ddd
{
void ddd.a'()
{
}
void eee.a'()
{
}
}
Compiler 1rror
a.cs(&2A): error C,0!"0: 7(((.eee.a&()7: containin) class does not implement interface 7eee7
<e &et an error as class """ is derived onl" rom interace ddd. -hus 'e cannot use eee.a1() as
interace eee is not a %ase interace or class """.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace ddd
{
void a'();
}
class yyy = ddd
{
void ddd.a'()
{
}
}
class ??? = yyy
{
void ddd.a'()
{
}
}
Compiler 1rror
a.cs(&92A): error C,0!"0: 7///.ddd.a&()7: containin) class does not implement interface 7ddd7
-he ke" concept earlier 'as that 'e could onl" use the name o an interace e8plicitl" i it 'as
cate&oricall" stated as a %ase class. An"thin& indirect 'ould not do. 3ere class """ is derived rom
interace ddd and thus 'e can use the orm ddd.a1. 3o'ever even thou&h class 888 is derived rom
class """ and thus also rom interace ddd$ 'e are not allo'ed to 'rite ddd.a1 as interace ddd is not
e8plicitl" stated in the derivation list o class 888.
An interace deines a contract and can onl" contain our entities viK methods$ properties$ events and
inde8ers. An interace thus cannot contain constants$ ields$ operators$ constructors$ destructors$ static
constructors$ or t"pes. Also an interace cannot contain static mem%ers o an" kind. -he modiiers
a%stract$ pu%lic$ protected$ internal$ private$ virtual$ override are disallo'ed as the" make no sense in
this conte8t.
243884333.doc 1LP od 221
a.cs
class zzz
{
2blic static void Main()
{
}
}
2blic dele;ate void d'();
2blic inter3ace aaa
{
void a'(strin; s);
int a*
{
;et; set ;
}
event d' ddd;
strin; t9isDint iE
{
;et; set;
} }
-he a%ove e8ample demonstrates the our entities an interace can contain. An"thin& else 'ill la& an
error.
a.cs
class zzz
{
2blic static void Main()
{
ccc c + ne8 ccc();
aaa a + c;
bbb b + c;
c.a'();c.a*();
a.a'();
b.a'();b.a*();
}
}
inter3ace aaa
{
void a'();
}
inter3ace bbb = aaa
{
void a*();
}
class ccc = bbb
{
2blic void a'()
{
System.Console.WriteLine("a'");
}
2blic void a*()
{
System.Console.WriteLine("a*");
}
}
:utput
a&
a
243884333.doc 1L8 od 221
a&
a&
a
An interace can also$ like a class$ inherit rom one or more interaces. !n this case %%% as an interace$
can inherit rom aaa. -he class ccc inherits rom interace %%% and and thus interace aaa has to
implement unctions a1 and a2. -he o%*ect c not onl" looks like a ccc %ut also looks like an aaa and
%%%. -hus e(uatin& them does not &ive an error. -he reverse$ ho'ever$ is not true. !t 'ill o%viousl"
la& an error. 3o'ever a can onl" access unctions rom the interace it %elon&s to$ in this case a1 and
% can access a1 and a2. % cannot access mem%ers rom class ccc even thou&h a$ %$ and c have the same
values. <henever an interace derives rom another it is called an e8plicit %ase interace. Hike classes$
circular deinitions are not permitted. !n act no'here in the CB pro&rammin& lan&ua&e are 'e
permitted to have circular deinitions.
An interace also creates a ne' t"pe and as in classes$ methods must have their o'n uni(ue si&natures.
2roperties and methods cannot have similar names.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void a'();
}
inter3ace bbb = aaa
{
void a'();
}
Compiler 8arnin)
a.cs(&52A): @arnin) C,0&03: 6he De(@ord ne@ is reHuired on 7===.a&()7 =ecause it hides
inherited mem=er 7aaa.a&()7
Hike classes i interaces derive rom each other$ there is a possi%ilit" that the" ma" contain the same
unction si&natures. -hus 'e &et a 'arnin& 'hich can %e removed %" addin& the ke"'ord ne' as
ollo's.
inter3ace bbb = aaa
{
ne8 void a'();
}
-he point to %e stressed here is that the ke"'ord ne' reall" does not do much$ other than remove the
'arnin&. -his is %ecause the implementation o the interace is done in the class. -here$ 'e 'ill have
onl" one implementation o unction a1 and not t'o$ one or aaa and the other or %%%. At one level$
rom the point o vie' o the class 'hich derives rom interace %%%$ it 'ill see onl" one unction in it$
not t'o. All that 'e are doin& is hidin& the %ase interace mem%er.
a.cs
class zzz
{
2blic static void Main()
{
243884333.doc 1LD od 221
}
void abc(ccc c)
{
c.aa(');
((bbb)c).aa(');
((aaa)c).aa(');
c.aa + *;
((aaa)c).aa + ,;
((bbb)c).aa + ,;
}
}
inter3ace aaa
{
int aa
{
;et; set;
}
}
inter3ace bbb
{
void aa(int i);
}
inter3ace ccc = aaa ) bbb
{
}
Compiler 1rror
a.cs(32&): error C,09: +m=i)uit( =et@een 7aaa.aa7 and 7===.aa(int)7
a.cs(&02&0): error C,0&&3: 7aaa.aa7 denotes a 7propert(7 @here a 7method7 @as e/pected
a.cs(&&2&): error C,09: +m=i)uit( =et@een 7aaa.aa7 and 7===.aa(int)7
a.cs(&52&0): error C,0A!": Method 7===.aa(int)7 referenced @ithout parentheses
!nterace aaa has onl" one mem%er$ a propert" called aa$ 'hereas interace %%% has one unction called
aa. -he interace ccc does not &ive us an error in spite o the act that 'e have a propert" and a
unction 'ith the same name. !n the unction a%c$ 'e are passin& c$ an o%*ect that looks like ccc. -he
line c.aa(1) &ives us an error as 'e have a propert" and a unction called aa. CB &ets conused 'hether
it is the propert" or the unction 'e are reerrin& to. !n our hum%le opinion$ 'e could onl" %e reerrin&
to the unction as per the s"nta8$ %ut "ou don:t ar&ue 'ith a compiler.
!n the second case c.aa T 2 also la&s an error due to the name conusion. !n this case also$ 'e could
onl" %e reerrin& to a propert". -he onl" 'a" out is to cast. -he second cast in each case &ives an error
as the s"nta8 or callin& a unction and propert" is dierent. /ormall"$ to cast$ 'e need to &ive t'o
sets o %rackets.
A cast incurs no run time costs i.e.$ it does not slo' do'n the pro&ram. All that a cast does in the
a%ove case is lo'ers the pointer rom a ccc to aaa or %%% at compile time. !n an earlier e8ample$ 'e
spoke o unctions rom t'o interaces havin& similar names. -he same rules stated there appl" here
also.
a.cs
class zzz
{
2blic static void Main()
{
}
void abc(ccc c)
{
c.aa(');
243884333.doc 1P+ od 221
c.aa((byte)');
((aaa)c).aa(');
((bbb)c).aa(');
}
}
inter3ace aaa
{
void aa(byte i);
}
inter3ace bbb
{
void aa(s9ort i);
}
inter3ace ccc = aaa ) bbb
{
}
Compiler 1rror
a.cs(32&): error C,0&&: 6he call is am=i)uous =et@een the follo@in) methods or properties:
7===.aa(short)7 and 7aaa.aa(=(te)7
a.cs(92&): error C,0&&: 6he call is am=i)uous =et@een the follo@in) methods or properties:
7===.aa(short)7 and 7aaa.aa(=(te)7
<e have a similar pro%lem a&ain. c.aa(1) does not kno' 'hich unction aa to call. CB could convert
the 1 an int$ either to a short or a %"te. -hus the am%i&uit". 0ven i 'e cast the 1 to a %"te$ or some
reason$ CB "et &ives us an error. -he onl" 'a" out is like 'hat 'e did earlier$ e8plicitl" cast "our 'a"
out o trou%le. <hen 'e cast$ 'e are restrictin& ourselves to onl" one method and thus no am%i&uit".
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void aa();
}
inter3ace bbb = aaa
{
ne8 void aa();
}
inter3ace ccc = aaa
{
void cc();
}
inter3ace ddd = bbb ) ccc
{
}
class eee = ddd
{
}
Compiler 1rror
a.cs(27): error C,0!5!: 7eee7 does not implement interface mem=er 7===.aa()7
a.cs(27): error C,0!5!: 7eee7 does not implement interface mem=er 7ccc.cc()7
a.cs(27): error C,0!5!: 7eee7 does not implement interface mem=er 7aaa.aa()7
243884333.doc 1P1 od 221
-he interace aaa has one unction aa. -he interace %%% is derived rom aaa and also has one unction
called aa. -he ke"'ord ne' inorms the CB compiler that$ it has hidden or has nothin& to do 'ith the
unction aa in interace aaa. 1emem%er in interaces$ 'e cannot 'rite an" code. -he interace ccc also
derives rom aaa %ut does not have a unction called aa. -hen 'e are creatin& another interace ddd
'hich derives rom %oth %%% and ccc. -he class eee is then derived rom interace ddd. <e &et three
errors as 'e have to implement three unctions in class eee. -he interace ccc %rin&s in t'o unctions.
.ne cc and the other aa rom interace aa. -he interace %%% has onl" one unction$ aa 'hich is
dierent rom the aa 'hich is present in interace aaa$ thanks to the ke"'ord ne' 'hich is optional.
a.cs
class zzz
{
2blic static void Main()
{
aaa a + ne8 eee();
a.aa();
bbb b + ne8 eee();
b.aa();
ccc c + ne8 eee();
c.aa();
ddd d + ne8 eee();
d.aa();
eee e + ne8 eee();
NNe.aa();
((aaa)d).aa();
((bbb)d).aa();
((ccc)d).aa();
((ddd)d).aa();
}
}
inter3ace aaa
{
void aa();
}
inter3ace bbb = aaa
{
ne8 void aa();
}
inter3ace ccc = aaa
{
void cc();
}
inter3ace ddd = bbb ) ccc
{
}
class eee = ddd
{
void aaa.aa()
{
System.Console.WriteLine("aa aaa");
}
void bbb.aa()
{
System.Console.WriteLine("aa bbb");
}
2blic void cc()
{
System.Console.WriteLine("cc");
243884333.doc 1P2 od 221
}
}
:utput
aa aaa
aa ===
aa aaa
aa ===
aa aaa
aa ===
aa aaa
aa ===
<ith or 'ithout the ke"'ord ne'$ the output remains the same. B" addin& the ke"'ord ne'$ all that
'e have achieved is removal o the 'arnin&. Hets e8plain the a%ove pro&ram step %" step.
<e have implemented the three unctions that class eee needed. <e could have implemented onl" one
aa$ and then in ever" case that one aa$ 'ould have %een called. !n this case 'e need t'o aa unctions.
.ne or the interace aaa and the other or the interace %%%. As 'e need a separate unction aa or
each interace 'e 'ill land up havin& t'o o them. -hus 'e need to preace them 'ith the name o the
interace.
<e are creatin& o%*ects that look like all our interaces and initialiKin& them to an o%*ect that looks like
class eee. -he o%*ect a that looks like interace aaa$ 'ill o%viousl" call the aa o interace aaa. -he
o%*ect % that looks like interace %%% 'ill call the aa o interace aaa implemented in class eee. -he
o%*ect c$ that looks like ccc is derived rom interace aaa and thus it 'ill call the unction aa o
interace aaa. All o this is o%vious. /o' d looks like ddd 'hich is derived rom ccc and %%%. -he
reason it 'ill call the aa o %%% and not o aaa is %ecause 'e have asked it to hide the unction aa o
interace aaa. .nce a unction is hidden$ it 'ill remain hidden orever in all the access paths. -hus
unction aa o interace %%% hides the unction aa o interace aaa even in interace ccc.
-he castin& &ives us the same ans'er as a%ove. !n the irst case$ cast d$ a ddd looks alike to an aaa.
-hus the aa rom aaa &ets called. !n the second case it calls the aa o %%%. 5ust like %eore$ 'hen 'e
cast c to a ccc$ it calls the aa orm aaa . /o' 'e cast c to a ddd$ it can call either the unction aa rom
%%% or unction aa rom aaa. !n this case it chooses to call the aa rom %%% as its aa hides the aa o
interace aaa.
-o sum up$ i a unction is hidden rom one access path$ it is hidden rom all.
A little later in this chapter$ 'e 'ill sho' "ou that structures can also implement rom an
interace.-his process o implementin& all the unctions is called interace mappin&.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void a'();
}
inter3ace bbb = aaa
{
ne8 int a'
{
set;
243884333.doc 1P3 od 221
}
}
class ccc = bbb
{
void aaa.a'()
{
}
int bbb.a' {
set
{
}
}
}
class ddd= bbb
{
2blic void a'() {}
int bbb.a'
{
set
{
}
}
}
class eee= bbb
{
void aaa.a'()
{
}
2blic int a'
{
set
{
}
}
}
-he interace aaa has one unction a1 'hich clashes 'ith the name o the propert" in interace %%%. <e
have three 'a"s to create a class 'hich is derived rom %%%. !n the irst case ccc$ 'e are e8plicitl"
(uali"in& 'ith the name o interace. !n the second case o ddd$ 'e are (uali"in& onl" the propert"
and not the unction. !n the third case i.e. class eee$ 'e do the reverse. -hus one o the a1or %oth must
%e (ualiied or else it 'ill result in an error.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void a'();
}
inter3ace bbb = aaa
{
void a*();
}
inter3ace ccc = aaa
{
243884333.doc 1P4 od 221
void a,();
}
class ddd = aaa)bbb)ccc
{
void bbb.a'()
{
}
2blic void a*()
{
}
2blic void a,()
{
}
}
Compiler 1rror
a.cs(&2A): error C,0!59: 7===.a&7 in e/plicit interface declaration is not a mem=er of interface
a.cs(&927): error C,0!5!: 7ddd7 does not implement interface mem=er 7aaa.a&()7
Both interaces %%% and ccc derive rom interace aaa. Class ddd derives rom three interaces aaa and
%%% and ccc. !n class ddd$ 'e have onl" 3 unctions$ a1$ a2 and a3 that come rom aaa$ %%% and ccc
respectivel". 0ven thou&h interace %%% derives rom aaa$ it does not carr" a1 into class ccc. So$ 'e
cannot 'rite %%%.a1 in class ccc. 3ence$ 'e have onl" one a1 rom interace aaa in class ccc and none
rom interaces %%% and ccc. -his proves that CB or&ets the interaces %%% and ccc are derived rom. !t
also means that %%% and ccc cannot have their o'n implementations o a1.
a.cs
class zzz
{
2blic static void Main()
{
aaa a + ne8 ccc();
a.a'();
}
}
inter3ace aaa
{
void a'();
}
class bbb
{
2blic void a'()
{
System.Console.WriteLine("bbb a'");
}
}
class ccc = bbb ) aaa
{
}
:utput
=== a&
-he class ccc derives rom %%% and aaa. -he unction a1 rom interace aaa is implemented %" class
%%% and not %" ccc. /o one cares as lon& as there is a unction a1 some'here. -he unction a1$ in this
case$ can %e in the actual class or in the %ase class.
a.cs
243884333.doc 1PE od 221
class zzz
{
2blic static void Main()
{
bbb b + ne8 ccc();
b.a'();
ccc c + ne8 ccc();
c.a'();
aaa a + ne8 ccc();
a.a'();
aaa aa + ne8 bbb();
aa.a'();
}
}
inter3ace aaa
{
void a'();
}
class bbb = aaa
{
2blic void a'()
{
System.Console.WriteLine("bbb a'");
}
}
class ccc = bbb
{
ne8 2blic void a'() {
System.Console.WriteLine("ccc a'");
}
}
:utput
=== a&
ccc a&
=== a&
=== a&
!n this case$ class ccc is derived rom class %%%$ 'hich in turn is derived rom interace aaa. Both the
classes implement the unction a1. -he (uestion on our minds is rom 'hich class 'ill the unction a1
%e called. Both % and c are initialiKed to an o%*ect that looks like ccc. %.a1() 'ill o%viousl" call the
unction a1 rom %%% and c.a1() 'ill call it rom ccc. Sa"in& the same thin& over and over a&ain like a
malunctionin& record disk is tr"in& %ut essential.
.%*ects a and aa look like aaa %ut are initialiKed to o%*ects that look like ccc and %%% respectivel". !t
does not seem to make an" dierence as each time the unction a1 &ets called rom the %ase class %%%
and not rom the derived class ccc or the class that 'e have initialiKed the o%*ect to.
-his means that the derived class cannot alter the interace mappin&s it receives rom the %ase class.
-he mappin& o unction a1 is to the class %%% as %%% 'as derived rom the interace. Class ccc cannot
chan&e this act.
a.cs
class zzz
{
2blic static void Main()
{
bbb b + ne8 ccc();
b.a'();
243884333.doc 1PL od 221
bbb b' + ne8 bbb();
b'.a'();
ccc c + ne8 ccc();
c.a'();
aaa a + ne8 ccc();
a.a'();
aaa aa + ne8 bbb();
aa.a'();
}
}
inter3ace aaa
{
void a'();
}
class bbb = aaa
{
2blic virt2al void a'()
{
System.Console.WriteLine("bbb a'");
}
}
class ccc = bbb
{
2blic override void a'()
{
System.Console.WriteLine("ccc a'");
}
}
:utput
ccc a&
=== a&
ccc a&
ccc a&
=== a&
<e have made t'o chan&es in our pro&ram. <e made the unction a1 virtual in the class %%% and also$
in the class ccc$ 'e declared a1 'ith the override modiier. <henever 'e declare a unction to %e
virtual$ the derived classes 'ill and can override it. -he modiier override has the opposite meanin&
over ne'. !t means do not create a ne' unction %ut override the %ase class deinition.
.%*ects % and %1 %oth look like %%% %ut are initialiKed to o%*ects that look like ccc and %%%
respectivel". <hen 'e 'rite %.a1()$ CB irst looks into the class %%% as that is the data t"pe o %. 3ere
the unction a1 is marked virtual$ so CB no' asks 4'hat 'as % initialiKed %"7? As the ans'er is an
o%*ect that looks like ccc$ CB no' looks at the class ccc or the unction a1. As it is marked override$
CB 'ill e8ecute the unction a1 rom class ccc and not %%%. ! the override 'as missin&$ the deault is
ne'$ and the unction 'ill %e called rom the data t"pe o the o%*ect i.e. %%%.
As o%*ect %1 has %een initialiKed %" an o%*ect that looks like %%%$ CB 'ill call a1 rom class %%% onl".
-he o%*ect c ollo's the earlier speciied rules. As or o%*ects a and aa$ %oth look like interace aaa
'hich has no code or the unction aaa. 3ere the o%*ect used to initialiKe 'ill decide the class a1 'ill
%e called rom. -his is due to the e8planation a%ove as a1 is marked virtual in class %%% and override
in class ccc.
a.cs
class zzz
{
2blic static void Main()
243884333.doc 1PP od 221
{
}
}
inter3ace
{
void a'();
}
inter3ace aaa
{
void a'();
}
class bbb = aaa )
{
2blic virt2al void aaa.a'()
{
System.Console.WriteLine("bbb a'");
}
}
class ccc = bbb
{
2blic override void a'() {
System.Console.WriteLine("ccc a'");
}
}
Compiler 1rror
a.cs(&72&): error C,0&0A: 6he modifier 7pu=lic7 is not %alid for this item
a.cs(&72&): error C,0&0A: 6he modifier 7%irtual7 is not %alid for this item
Hets make matters 'orse. <e have an interace ppp 'hich also %rin&s in a unction called a1. -he
class %%% also derives rom ppp. -hus 'e have t'o a1 unctions and 'e have to e8plicitl" (uali"
them. ;nortunatel" 'e cannot add the (ualiier virtual here. -he onl" 'a" out is as ollo's.
a.cs
class zzz
{
2blic static void Main()
{
aaa a + ne8 ccc();
a.a'();
aaa aa + ne8 bbb();
aa.a'();
}
}
inter3ace
{
void a'();
}
inter3ace aaa
{
void a'();
}
class bbb = aaa )
{
void aaa.a'()
{
aa'();
}
void .a'()
243884333.doc 1P8 od 221
{
}
2blic virt2al void aa'()
{
System.Console.WriteLine("aa'");
}
}
class ccc = bbb
{
2blic override void aa'()
{
System.Console.WriteLine("aa' ccc");
}
}
:utput
aa& ccc
aa&
<hat 'e have done here is that in the a1 unction o aaa 'e have called the unction aa1. So in other
'ords$ a1 simpl" calls aa1. <e have made aa1 virtual such that each time aa1 is called$ the (uestion
asked 'ill %e 6 'hich o%*ect 'as used at the time o initialiKation? >ependin& upon the t"pe o o%*ect$
the relevant unction aa1 'ould %e e8ecuted. -hus 'e &et the same ans'er as earlier. ! 'e have to
reimplement an interace$ "ou can look at the e8ample earlier. CB or&ets a%out the initial derivation.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void a'();
void a*();
}
abstract class bbb = aaa
{
}
Compiler 1rror
a.cs(&2&A): error C,0!5!: 7===7 does not implement interface mem=er 7aaa.a&()7
a.cs(&2&A): error C,0!5!: 7===7 does not implement interface mem=er 7aaa.a()7
<henever 'e have a a%stract class derivin& rom an interace$ the class must implement all the
methods o the interace as ollo's.
a.cs
class zzz
{
2blic static void Main()
{
}
}
inter3ace aaa
{
void a'();
243884333.doc 1PD od 221
void a*();
}
abstract class bbb = aaa
{
2blic void a'()
{
}
2blic abstract void a*();
}
! the a%stract class does not 'ant to implement all the mem%ers o the interace$ it has to mark the
unctions as a%stract and pu%lic. -he class derivin& rom %%% 'ill no' have to suppl" the code o the
class %%%
Structures
a.cs
class zzz
{
2blic static void Main()
{
??? ? + ne8 ???('();
System.Console.WriteLine(?.i);
?.abc();
}
}
str2ct ???
{
2blic int i;
2blic ???( int 4)
{
i + 4;
}
2blic void abc()
{
System.Console.WriteLine("abc");
}
}
:utput
&0
a=c
A structure or struct to %e precise is similar to a class in man" 'a"s. A struct can contain ields$
methods etc. ! a struct and class 'ere 1++ per cent similar$ then 'h" have %oth? <e 'ill no' e8plain
the dierences %et'een a struct and a class. ;nless other'ise stated$ the" share the same eatures.
a.cs
class zzz
{
2blic static void Main()
{
}
}
str2ct ???
{
2blic int i + '(;
}
243884333.doc 18+ od 221
Compiler 1rror
a.cs(92&): error C,0!75: 7///.i7: cannot ha%e instance field initiali9ers in structs
!n a class 'e are allo'ed to create a ieldNvaria%le and initialiKe it at the same time. A structure cannot
contain such initialiKations. -hus these ields must %e initialiKed either throu&h unctions or %" usin&
the o%*ect itsel. #ields cannot %e &iven initial values at the time o creation.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
}
}
str2ct ???
{
2blic int i;
2blic ???()
{
}
}
Compiler 1rror
a.cs(&&23): error C,0!A3: ,tructs cannot contain e/plicit parameterless constructors
A class can contain man" constructors. And even i 'e do not have an"$ CB supplies a ree constructor
'ith no parameters. !t:s ver" dierent 'ith structures. Gou cannot have a constructor 'ith no
parameters. ! "ou do$ "ou 'ill &et the a%ove error. -hus CB lets "ou have as man" constructors as "ou
like %ut none 'ithout parameters.
a.cs
class zzz
{
2blic static void Main() {
??? a + ne8 ???('();
}
}
str2ct ???
{
2blic int i;
2blic ???(int ) { }
}
Compiler 1rror
a.cs(&023): error C,0&7&: Bield 7///.i7 must =e full( assi)ned =efore control lea%es the
constructor
A small pro%lem here. As mentioned earlier 'e cannot initialiKe a ield like 'e do in a class. 3ence CB
insists on constructors that accept parameters to initialiKe ieldsM at the end o the constructor i "ou
have not initialiKed the ields in the structure$ 'e &et the a%ove error. -hus CB actuall" reads our code
and makes sure that the constructor initialiKes all the ields in the structure.
a.cs
class zzz
{
2blic static void Main()
{
243884333.doc 181 od 221
??? a + ne8 ???('();
}
}
str2ct ???
{
2blic int i)4;
2blic ???(int ) {
i + ;
}
}
Compiler 1rror
a.cs(&&23): error C,0&7&: Bield 7///.E7 must =e full( assi)ned =efore control lea%es the
constructor
-he ke"'ord sho'n in all the a%ove errors is ields.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???('();
}
}
str2ct ???
{
2blic int i)4;
2blic ???(int )
{
i + ;
4 + (;
}
}
<e &et no error as the structure has t'o ields and 'e have no' initialiKed %oth o them.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
System.Console.WriteLine(a.i);
}
}
str2ct ???
{
2blic int i;
}
Compiler 8arnin)
a.cs(&&2&): @arnin) C,0A"9: Bield 7///.i7 is ne%er assi)ned to2 and @ill al@a(s ha%e its default
%alue 0
:utput
0
! 'e do not have an" constructors$ 'e &et no error. As 'e have not initialiKed the ield i$ in the
constructor$ 'e have none. CB &ives "ou a 'arnin& and or the sake o "our sanit"$ initialiKes i to +.
243884333.doc 182 od 221
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 ???();
System.Console.WriteLine(a.i);
}
}
str2ct ???
{
2blic int i;
}
str2ct yyy = ???
{
}
Compiler 1rror
a.cs(&52&"): error C,0!7: 7///7 : t(pe in interface list is not an interface
A structure """ cannot %e derived rom another structure. A useul eature o a class 'as the act that
'e could shareNuse code rom other classes. A structure does not support the concept o inheritance.
3ad 888 %een a class 'e 'ould have received the same error.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 yyy();
}
}
inter3ace ???
{
}
str2ct yyy = ???
{
}
-he previous error messa&e &ave us a hint . !t e8pected 888 to %e a interace. -hus 'e can derive a
structure rom an interace. As 888 has no mem%ers 'e do not have to implement an" code in our
structure.
a.cs
class zzz
{
2blic static void Main()
{
??? a + ne8 yyy();
}
}
str2ct yyy
{
}
class ??? = yyy
{
}
243884333.doc 183 od 221
Compiler 1rror
a.cs(&&27): error C,0!09: 7///7 : cannot inherit from sealed class 7(((7
As a structure could not inherit rom a class$ the reverse is also true. 888 cannot inherit rom a
structure """. !nternall" a structure %ehaves as a sealed class as the error messa&e reads. #or those 'ho
came in late$ a sealed class cannot %e used a %ase class.
a.cs
class zzz
{
2blic static void Main()
{
}
}
sealed str2ct yyy
{
}
Compiler 1rror
a.cs(72&!): error C,0&0A: 6he modifier 7sealed7 is not %alid for this item
Gou cannot declare a structure as sealed as the" are %" deinition sealed. ! "ou add the 'ord sealed as
'e have done$ CB complains a%out the act that 'e are repeatin& the same modiier a&ain and no%od"
likes repetition.
a.cs
class zzz
{
2blic static void Main()
{
}
}
abstract str2ct yyy
{
}
Compiler 1rror
a.cs(72&7): error C,0&0A: 6he modifier 7a=stract7 is not %alid for this item
As CB does not like repetition$ 'e have to %o' to its 'ishes. But "ou do not have an option. <e are
ree to repeat ourselves 'ith "ou as man" times as 'e like. So let us indul&e ourselves. A structure as
mentioned earlier cannot %e used as a %ase class i.e. %e used in a derivation. An a%stract modiier$
means an incomplete entit" 'hich cannot %e used directl" %ut onl" as a %ase class. !t makes no sense
or a structure to use the modiier a%stract.
!n the same vein$ unction in a structure cannot %e marked a%stract or virtual as these are concepts$
'hich appl" to derived classes onl".
a.cs
class zzz
{
2blic static void Main()
{
}
}
rotected str2ct ??? { }
Compiler 1rror
243884333.doc 184 od 221
a.cs(72&): error C,&!7: Famespace elements cannot =e e/plicitl( declared as pri%ate or
protected
A structure cannot %e derived rom and the modiier protected deals 'ith the visi%ilit" o mem%ers
rom derived classes. 1eplacin& protected 'ith private results in the same error.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
System.Console.WriteLine(a.GoStrin;());
}
}
str2ct yyy
{
}
:utput
(((
3o'ever ever" structure like a class is implicitl" derived rom the class .%*ect and thus has the
unctions .%*ect contains. !n this case -oStrin& returns the name o the derived class.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
System.Console.WriteLine(a.GoStrin;());
}
}
str2ct yyy = System.@b4ect
{
}
Compiler 1rror
a.cs(92&"): error C,0!7: 7,(stem.:=Eect7 : t(pe in interface list is not an interface
3o' do 'e e8plain the a%ove error? <e *ust mentioned earlier that as a structure inherits rom the
class .%*ect and 'e called a unction called -oStrin& rom the class .%*ect. 3o'ever 'e cannot
derive rom .%*ect e8plicitl" as the compiler insists on the name o an interace and .%*ect is a name
o a class. -hese little (uirks make learnin& CB diicult. ! "ou replace the 'ord struct 'ith class in
the a%ove e8ample$ "ou 'ill not &et an error.
A computer has lots o memor". <e lo&icall" divide this memor" into t'o$ the stack and the heap.
9emor" denoted as the stack lives as lon& as the unction lives and heap memor" lives as lon& as "our
pro&ram runs. .%*ects$ instances o a class are allocated on the heap. -he" 'ill live or a lon& time.
-he" are also called reerence o%*ects. Structures are allocated on the stack %" ne' and live or a
shorter duration. <e call them value o%*ects. -his means that a structure directl" represents the data
'here as a o%*ect contains a reerence to the data. Structures thus oer a more eicient access to
varia%les than classes. !nt$ %ool and all the other %asic data t"pes are implemented as structures.
a.cs
243884333.doc 18E od 221
class zzz
{
2blic static void Main()
{
??? ?)y;
yyy a)b;
? + ne8 ???('); y + ne8 ???(*);
a + ne8 yyy('); b + ne8 yyy(*);
System.Console.WriteLine(?.i - " " - y.i - " " - a.i - " " - b.i);
? + y; a + b;
System.Console.WriteLine(?.i - " " - y.i - " " - a.i - " " - b.i);
?.i + '((; a.i + *((;
System.Console.WriteLine(?.i - " " - y.i - " " - a.i - " " - b.i);
}
}
class yyy
{
2blic int i;
2blic yyy(int 4)
{
i + 4;
}
}
str2ct ???
{
2blic int i;
2blic ???(int 4)
{
i + 4;
}
}
:utput
& &
&00 00 00
<e have created t'o o%*ects a and % 'hich look like a class """ and t'o structures 8 and " 'hich look
like 888. !n the constructors o each$ 'e are initialiKin& the ield i to 1 and 2 respectivel". -hen 'e are
e(uatin& the o%*ect a to % and the structure 8 to ". -his 'ill set the i o 8 to 2 rom 1 and also the i o a
to 2. -hus the second <riteHine displa"s all t'o:s. <e are no' chan&in& the i o 8$ 'hich is a structure
to 1++ and 'e realiKe that the i o "$ the structure it 'as initialiKed to remains the same. -hus 8.i is 1++
and ".i remains at 2.
#or classes it does not 'ork the same 'a". Chan&in& a.i to 2++$ someho' chan&es the i o % 'hich a
'as initialiKed to$ also to 2++. -his could onl" %e possi%le i 'hen 'e e(uate structures$ each has its
o'n cop" o the data. <hen 'e e(uate o%*ects$ no cop"in& takes place and no' o%*ect a reers to
o%*ect % in memor". Both a and % represent the same o%*ect. Chan&in& a chan&es %. A little later$ 'e
d'ell on this concept urther.
-he same rules o passin& parameters to a unction i.e. out and re that appl" to an int also appl" to a
structure as int is also a structure internall".
a.cs
class zzz
{
2blic static void Main()
{
243884333.doc 18L od 221
??? ?;
yyy a;
?+n2ll;
a+n2ll;
}
}
class yyy
{
}
str2ct ???
{
}
Compiler 1rror
a.cs(725): error C,0057: Cannot con%ert null to 7///7 =ecause it is a %alue t(pe
!n computer pro&rammin&$ a lar&e num%er o times 'e do not kno' the value o a varia%le at a point
in time. -hese varia%les are &iven a value o null. /ull can %e onl" applied to o%*ects o reerence
t"pes and not value t"pes.
a.cs
class zzz
{
2blic static void Main()
{
}
}
str2ct ???
{
2blic C???()
{
}
}
Compiler 1rror
a.cs(929): error C,0!7!: :nl( class t(pes can contain destructors
Ater a lon& time$ 'e &et an error messa&e that is reada%le. Structures are created on the stack
and die 'hen 'e reach the closin& %race. -here is thus no memor" mana&ement to %e done
rom the point o vie' o the pro&rammer. -he structure lie c"cle is ver" deterministic and
hence no destructors are permitted.
12
.perator .verloadin&
Het7s e8plain 'hat operator overloadin& is all a%out 'ith an e8ample o a class that represents a date.
<ould it not %e &reat i 'e could su%tract t'o date o%*ects and %e returned an int representin& the
num%er o da"s elapsin& %et'een the t'o dates. <e 'ould like to use the &ood old su%traction
operator ` like 'e do 'hen su%tractin& num%ers. Also 'e 'ould like the U operator to compare t'o
date o%*ects and tell us 'hich one is lar&er. -he , operator could add a num%er to a date resultin& in a
ne' date o%*ect.
243884333.doc 18P od 221
-hus$ operator overloadin& lets us redeine the e8istin& operators so that the" 'ork 'ith
classesNo%*ects 'e create like """. <e have not "et instructed CB on ho' to use the trust" old ,
operator 'ith t'o """ o%*ects. -hou&h CB kno's ho' to use the , to add t'o num%ers$ it does not
kno' ho' to add t'o """7s.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy c;
c + a - b ;
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
}
Compiler 1rror
a.cs(32!): error C,00&9: :perator .M0 cannot =e applied to operands of t(pe .(((0 and .(((0
<e have created a simple class """ 'hich has one instance varia%le i 'hich 'ill distin&uish dierent
instances o """ rom each other. -he constructor 'ith an int as a parameter initialiKes i. <e have tried
to add t'o o%*ects that look like """ 'hich does not &o do'n 'ell 'ith CB and it o%*ects to it.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy c;
c + a - b ;
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic yyy oerator - ( yyy ? ) yyy y)
{
}
}
Compiler 1rror
a.cs(&32&): error C,0!!3: Cser*defined operators .(((.operator M((((2 ((()0 must =e declared
static and pu=lic
243884333.doc 188 od 221
0rror messa&es can %e at times helpul. .ur operator , is pu%lic %ut not static. CB demands that all
operator overloads %e static.
a.cs
2blic class zzz
{
2blic static void Main() {
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy c;
c + a - b ;
System.Console.WriteLine(c.i);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4) {
i + 4;
}
2blic static yyy oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
yyy z + ne8 yyy(?.i-y.i);
ret2rn z;
}
}
:utput
operator M &0 !
&!
-he 'ord operator as the name o a unction$ is le&al and the onl" 'a" to overload operators. <e
ollo' this 'ord 'ith the operator 'e 'ant to overload and then the parameters 'e 'ill call the
operator 'ith. , is a %inar" operator and 'ill need t'o """7s$ one on its let and the other on its ri&ht.
-hen at %e&innin&$ 'e &ive the return value o the operator. !n our case 'e 'ant a , to add t'o """7s
and return a third """ 'hose i 'ill %e the sum o the individual i7s. -hus a,% 'ill call the operator ,
'ith 8 %ein& e(ual to a and " to %. -hus 8.i 'ill have a value 1+ and ".i$ E. <e are creatin& a ne'
o%*ect K and in the constructor passin& 1E i.e. 1+ , E. -hus the i o K 'ill %e 1E 'hich is %ein&
returned. a , % 'ill no' %e replaced %" the o%*ect 'hose i has a value 1E and c 'ill %e e(ual to this
o%*ect. -hus c.i 'ill %e e(ual to 1E.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy c;
c + a - b ;
System.Console.WriteLine(c.i);
}
}
2blic class yyy
{
2blic int i;
243884333.doc 18D od 221
2blic yyy( int 4)
{
i + 4;
}
2blic static yyy oerator + ( yyy ? ) yyy y)
{
}
2blic static yyy oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
yyy z + ne8 yyy(?.i-y.i);
ret2rn z;
}
}
Compiler 1rror
a.cs(&923): error C,&00: :%erloada=le =inar( operator e/pected
-he error messa&e is tellin& us that 'e cannot overload the assi&nment operator T. 0ver" class &ets a
ree assi&nment operator 'hich does a %it'ise cop" o the varia%les o the o%*ect rom the let to the
ri&ht.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy c + ne8 yyy(*);
yyy d;
d + a - b - c ;
System.Console.WriteLine(d.i);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static yyy oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
yyy z + ne8 yyy(?.i-y.i);
ret2rn z;
}
}
:utput
:perator M &0 !
:perator M &!
&7
-he onl" chan&e is d T a , % , c. CB &ets easil" conused 'ith comple8 statements so it does not read
all o it. !t sees t'o operators on the same line. !n this case$ the same plus. An internal rule tells it to
read the plus let to ri&ht i.e. it 'ill onl" see a , %. !t 'ill call the operator , 'ith 8.i as 1+ and ".i as E
%ecause a7s i is 1+ and %7s i is E. -his 'ill create a temporar" o%*ect like """ 'hose i is 1E$ lets call it
243884333.doc 1D+ od 221
KK. -he o%*ect K is ver" dierent rom KK. CB then evaluates KK , c. -hus 8.i 'ill displa" 1E and ".i 'ill
have the value o c.i i.e. 2. -o support multiple invocations o the operator on a sin&le line$ the code
does not chan&e.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
int d + a - b ;
System.Console.WriteLine(d);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static int oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
ret2rn ?.i - y.i;
}
}
:utput
operator M &0 !
&!
CB does not and 'ill never understand 'hat addition o t'o """7s is all a%out. !t is in "our hands to
decide 'hat the code accomplishes. Gou decide 'hether the overloaded , returns a """ or an int
o%*ect. -he class """ is "our creation not CB7s. 3ence "ou decide 'hat addition means in the conte8t
o a """ class. !n this case$ 'e are returnin& an int unlike earlier 'here 'e returned a """.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
int d + a - b ;
System.Console.WriteLine(d);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static int oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
243884333.doc 1D1 od 221
ret2rn ?.i - y.i;
}
2blic static yyy oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
yyy z + ne8 yyy(?.i-y.i);
ret2rn z;
}
}
Compiler 1rror
a.cs(52&9): error C,0&&&: Class .(((0 alread( defines a mem=er called . opW+ddition . @ith the
same parameter t(pes
Gou cannot have t'o operator , overloads 'hich onl" dier in return t"pes. Also the error messa&es
chan&e the name o the operator rom , to op\Addition. <hen 'e overloaded unctions$ the return
t"pe 'as not considered part o the unction si&nature. -he same applies or operators.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy d + a - b - *(;
System.Console.WriteLine(d.i);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static yyy oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
yyy z + ne8 yyy(?.i-y.i);
ret2rn z;
}
}
Compiler 1rror
a.cs(729): error C,00&9: :perator .M0 cannot =e applied to operands of t(pe .(((0 and .int0
CB is no' tellin& "ou that "ou can add t'o """7s %ut cannot do the same$ i.e. add a """ and an int as
'e have not told CB ho' to do so.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
yyy d + a - b - *(;
System.Console.WriteLine(d.i);
243884333.doc 1D2 od 221
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static yyy oerator - ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y.i);
yyy z + ne8 yyy(?.i-y.i);
ret2rn z;
}
2blic static yyy oerator - ( yyy ? ) int y)
{
System.Console.WriteLine(Qoerator - Q - ?.i - Q Q - y);
yyy z + ne8 yyy(?.i-y);
ret2rn z;
}
}
:utput
:perator M &0 !
:perator M &! 0
5!
Hie is un in the ast lane. As 'e could have a lar&e num%er o unctions 'ith the same name %ut
dierin& num%er o parameters$ ditto or operators. a , % as usual calls the irst operator ,. -his as
usual creates a temp o%*ect$ sa" KK and no' CB reads the line as KK , 2+. -his matches the second
operator , 'hich no' &ets called. Gou can have over a million plus operators 'ith dierin&
parameters i "ou desire.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
i3 ( a / b )
System.Console.WriteLine(Qtr2eR);
else
System.Console.WriteLine(Q3alseR);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static bool oerator / ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator 0 Q - ?.i - Q Q - y.i);
ret2rn ?.i / y.i;
}
243884333.doc 1D3 od 221
}
Compiler 1rror
a.cs(020): error C,0&A: 6he operator .(((.operator >((((2 ((()0 reHuires a matchin)
operator .U. to also =e defined
CB is a romantic at heart and loves pairs. <e tried to overload the U operator and CB tells us that 'e
have to also overload the V operator. !t makes sense as a user 'ould 'ant to kno' 'hether a """ is
&reater than or less than another """.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
yyy b + ne8 yyy(.);
i3 ( a / b )
System.Console.WriteLine(Qtr2eR);
else
System.Console.WriteLine(Q3alseR);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static bool oerator / ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator / Q - ?.i - Q Q - y.i);
ret2rn ?.i / y.i;
}
2blic static bool oerator 0 ( yyy ? ) yyy y)
{
System.Console.WriteLine(Qoerator 0 Q - ?.i - Q Q - y.i);
ret2rn ?.i 0 y.i;
}
}
:utput
operator > &0 !
true
-he operator V returns a %ool as 'e 'ould like to use it as part o an i or a 'hile. !n this case 'e are
usin& it as part o an i and nothin& stops us rom usin& the V overloaded or ints and """7s to return a
%ool. <hat code "ou 'rite in an operator is entirel" "our decision. -he V operator looks like the , and
can take dierent parameters. -o overload the FT$ "ou also have to overload the TT.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
System.Console.WriteLine(a);
System.Console.WriteLine(a.GoStrin;());
243884333.doc 1D4 od 221
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
}
:utput
(((
(((
!n the irst <riteHine unction to %e called$ 'e are passin& the o%*ect a 'hereas the irst parameter to
<riteHine should %e a strin&. Also 'e do not &et an error and 'e see """ displa"ed. A lon&time %ack
'e told "ou that all classes inall" derive rom o%*ect. -he class o%*ect has a unction -oStrin&. -hus
callin& the -oStrin& unction o a produces the same output as the a%ove line. <e have not created the
-oStrin& unction. So either 'e &ot a ree -oStrin& implementation rom CB like 'e &et a ree
Constructor or the -oStrin& unction o o%*ect in some 'a" determines the name o our class and
returns it as a strin&.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
System.Console.WriteLine(a);
System.Console.WriteLine(a.GoStrin;());
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
Compiler 8arnin)
a.cs(&72&!): @arnin) C,0&&": .(((.6o,trin)()0 hides inherited mem=er .o=Eect.6o,trin)()0. 6o
maDe the current method o%erride that implementation2 add the o%erride De(@ord. :ther@ise
add the ne@ De(@ord.
!t is the same 'arnin& i a unction e8ists in the %ase class.
:utput
(((
6o,trin)
243884333.doc 1DE od 221
muDhi
<riteHine displa"s """ and a.-oStrin& displa"s mukhi. <hich means that the" call dierent -oStrin&
unctions. -he <riteHine(a) calls the -oStrin& o o%*ect 'hereas the second <riteHine calls it o """.
! 'e 'ant to override a unction in the %ase class$ 'e have to speciicall" do so %" usin& the modiier
override. ! 'e do not$ the deault is to call the %ase class -oStrin&. All this has %een e8plained earlier$
in an" case.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
System.Console.WriteLine(a);
System.Console.WriteLine(a.GoStrin;());
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
6o,trin)
muDhi
6o,trin)
muDhi
/o' %oth the S"stem.Console.<riteHine calls the -oStrin& unction o """. <e 'ould like to convert
a """ into a strin& or an int or e8ample. -hese t"pe conversions are a ma*or part o operator
overloadin&.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
System.Console.WriteLine(a);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static imlicit oerator strin;(yyy y)
243884333.doc 1DL od 221
{
System.Console.WriteLine(Qoerator strin;R);
ret2rn Qstrin; Q - y.i;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
operator strin)
strin) &0
!n spite o havin& a unction -oStrin&$ it does not &et called unlike earlier. Ater the ke"'ord operator
'e have the name o a data t"pe i.e. strin&. -his unction is called 'henever 'e 'ant to convert our
o%*ect into a strin&. -he parameter " stands or the o%*ect to %e converted. !n this unction 'e can 'rite
'hatever code 'e 'ant to %ut 'e must return a strin&. !n our case 'e return the te8t strin&
concatenated 'ith the current value o i.
.nce a&ain$ the <riteHine unction re(uires a strin& class. <e are oerin& a """ class. CB checks
'hether there is an operator strin& 'hich is availa%le to convert a """ into a strin&. As there is one$ it
&ets called. -he 'ord implicit means that 'e are indirectl" impl"in& that it should %e called. Hets
e8plain this 'ith another e8ample.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
strin; s;
s + a;
System.Console.WriteLine(s);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static e?licit oerator strin;(yyy y)
{
System.Console.WriteLine(Qoerator strin;R);
ret2rn Qstrin; Q - y.i;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
Compiler 1rror
a.cs(72!): error C,009: Cannot implicitl( con%ert t(pe .(((0 to .strin)0
243884333.doc 1DP od 221
<e have chan&ed the 'ord implicit 'hich means impl". !t also means &ivin& a hint 'ith the 'ord
e8plicit 'hich means speci". 3ad 'e not chan&ed implicit 'ith e8plicit$ 'e 'ould have &ot no error
and CB 'ould have called the operator to convert a into a strin& and initialiKe s to it.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
strin; s;
s + (strin;)a;
System.Console.WriteLine(s);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static e?licit oerator strin;(yyy y)
{
System.Console.WriteLine(Qoerator strin;R);
ret2rn Qstrin; Q - y.i;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
operator strin)
strin) &0
-he () is called a cast and it takes an" data t"pe 'ithin %rackets. <e are e8plicitl" askin& or a
conversion to a strin& and unlike earlier 'e are not %ein& implicit %ut e8plicit.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
strin; s;
s + (strin;)a;
System.Console.WriteLine(s);
System.Console.WriteLine(a);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
243884333.doc 1D8 od 221
i + 4;
}
2blic static e?licit oerator strin;(yyy y)
{
System.Console.WriteLine(Qoerator strin;R);
ret2rn Qstrin; Q - y.i;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
operator strin)
strin) &0
6o,trin)
muDhi
-he e8plicit 'ill &et called onl" 'hen 'e cast and as 'e do not have an implicit modiier$ the -oStrin&
&ets called. <e &et no error i 'e do not have an implicit modiier.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy('();
strin; s;
s + (strin;)a;
System.Console.WriteLine(s);
System.Console.WriteLine(a);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic static e?licit oerator strin;(yyy y)
{
System.Console.WriteLine(Qoerator strin;R);
ret2rn Qstrin; Q - y.i;
}
2blic static imlicit oerator strin;(yyy y)
{
System.Console.WriteLine(Qoerator strin;R);
ret2rn Qstrin; Q - y.i;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
243884333.doc 1DD od 221
Compiler 1rror
a.cs("2&!): error C,0!!7: Iuplicate user*defined con%ersion in class .(((0
<e cannot have %oth the implicit and e8plicit modiier as t'o separate unctions. -hus "ou have to
decide 'hich one "ou 'ould 'ant to implement.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a ;
a + '(;
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
a.cs(72!): error C,009: Cannot implicitl( con%ert t(pe .int0 to .(((0
.ne more error. 3ere 'e are tr"in& to e(uate a """ to an int %ut unlike earlier$ 'e have not created an
o%*ect like """ %" sa"in& ne'. <e 'ould need someone to create the """ o%*ect and initialiKe it to 1+$
an int.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a ;
a + '(;
System.Console.WriteLine(a.i);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
static 2blic imlicit oerator yyy(int v)
{
System.Console.WriteLine(Qoerator yyy int Q - v);
yyy z + ne8 yyy(v);
ret2rn z;
}
243884333.doc 2++ od 221
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
operator ((( int &0
&0
A constructor has the same name as the name o the class. -hus operator """ ma" dou%le up as a
constructor. <hen 'e 'rite a T 1+$ CB calls this constructor and passes the parameter v a value$ 1+.
.perator """ has no' to create an o%*ect that looks like """ and return it. -hus it does not act like a
constructor in the sense that a constructor is responsi%le or creatin& the o%*ect. !n other 'ords$
'ritin& a T 1+$ creates a ne' o%*ect that looks like """ and initialiKes it to 1+. !t is dierent rom 'hat
'e did earlier as previousl" the operator did not have to create an o%*ect that looks like """. !n this
case it has to.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy a ;
a + QHiR;
System.Console.WriteLine(a.i);
}
}
2blic class yyy
{
2blic int i;
2blic yyy( int 4)
{
i + 4;
}
static 2blic imlicit oerator yyy(int v)
{
System.Console.WriteLine(Qoerator yyy int Q - v);
yyy z + ne8 yyy(v);
ret2rn z;
}
static 2blic imlicit oerator yyy(strin; v)
{
System.Console.WriteLine(Qoerator yyy strin; Q - v);
yyy z + ne8 yyy('(();
ret2rn z;
}
2blic override strin; GoStrin;()
{
System.Console.WriteLine(QGoStrin;R);
ret2rn Qm2<9iR;
}
}
:utput
operator ((( strin) ;i
&00
243884333.doc 2+1 od 221
<e can have as man" operator """ unctions as 'e like$ provided 'e ollo' the rules o unction
overloadin&. -hus 'e have t'o o them$ one that takes a strin&$ another that takes an int. !n this case
as 'e are 'ritin& a T ^hi_$ the second operator that accepts a strin& &et called. -he" all have to return
an o%*ect that looks like """.
a + (s9ort) '(;
3ad 'e 'ritten the a%ove line$ 'e 'ill not &et an" errors. <e assumed 'e 'ill &et an error as
'e do not have an operator """ 'hich takes a short as a parameter. CB is hi&hl" intelli&ent. !t
irst checks 'hether 'e have an operator """ that matches 'hat 'e 'rote. !n no case$ there is
a match. !t 'ill then check 'hether there is an" other 'a" it can prevent an error rom %ein&
si&naled. CB realiKes that there is an operator """ 'hich accepts an int. -hus it converts a
short to an int and then calls the operator """ 'ith the int parameter.
13
Collection .%*ects
0arlier 'e used an arra" in a oreach. ! the arra" had three mem%ers$ the oreach &ot e8ecuted three
times and each time the varia%le i had a dierent value. -he concept descri%ed %elo' is called a
collection class. !t is a class that returns a value each time till the values run out$ thus makin& it easier
or us to iterate throu&h the arra".
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy 3 + ne8 yyy();
3oreac9 (strin; i in 3)
{
}
}
}
class yyy
{
}
Compiler 1rror
a.cs(A2&): error C,&!79: foreach statement cannot operate on %aria=les of t(pe .(((0 =ecause
.(((0 does not contain a definition for .Qet1numerator02 or it is inaccessi=le
-o use """ in a oreach as a collection class$ oreach re(uires a unction @et0numerator.
a.cs
2blic class zzz
{
2blic static void Main()
{
yyy 3 + ne8 yyy();
3oreac9 (strin; i in 3)
{
243884333.doc 2+2 od 221
}
}
}
class yyy
{
2blic int LetBn2merator()
{
}
}
Compiler 1rror
a.cs(A2&): error C,&!79: foreach statement cannot operate on %aria=les of t(pe 7(((7 =ecause
7int7 does not contain a definition for 7Mo%eFe/t72 or it is inaccessi=le
a.cs(&52&): error C,0&A&: 7(((.Qet1numerator()7: not all code paths return a %alue
#oreach o%viousl" tries to e8ecute the unction called @et0numerator. -his unction should not return
an int %ut somethin& else as the error su&&ests.
a.cs
2sin; System.Collections;
2blic class zzz
{
2blic static void Main()
{
yyy 3 + ne8 yyy();
3oreac9 (strin; i in 3)
{
}
}
}
class yyy
{
2blic "Bn2merator LetBn2merator()
{
ret2rn ne8 ???();
}
}
class ??? = "Bn2merator
{
}
Compiler 1rror
a.cs(&927): error C,0!5!: .///0 does not implement interface mem=er
.,(stem.Collections.>1numerator.Mo%eFe/t()0
a.cs(&927): error C,0!5!: .///0 does not implement interface mem=er
.,(stem.Collections.>1numerator.Reset()0
a.cs(&927): error C,0!5!: .///0 does not implement interface mem=er
.,(stem.Collections.>1numerator.Current0
!0numerator is an interace 'hich has three unctions 9ove/e8t$ 1eset and Current and 888 has to
implement all o them to remove the compiler errors.
a.cs
2sin; System.Collections;
2blic class zzz
{
243884333.doc 2+3 od 221
2blic static void Main()
{
yyy 3 + ne8 yyy();
3oreac9 (strin; i in 3)
{
System.Console.WriteLine(i);
}
}
}
class yyy
{
2blic "Bn2merator LetBn2merator()
{
ret2rn ne8 ???();
}
}
class ??? = "Bn2merator
{
2blic bool MoveJe?t()
{
System.Console.WriteLine(QMoveJe?tR);
ret2rn tr2e;
}
2blic void &eset()
{
System.Console.WriteLine(Q&esetR);
}
2blic ob4ect C2rrent
{
;et
{
System.Console.WriteLine(QC2rrentR);
ret2rn Q9iR;
}
}
}
1un the pro&ram and "ou 'ill notice that the output does not stop. !t &oes on orever.
!0numerator is an interace 'hich %elon&s to the namespace S"stem.Collections. oreach irst calls the
unction @et0numerator rom """. !t e8pects this unction to return an o%*ect like !0numerator. !t then
calls the unction 9ove/e8t rom this returned o%*ect. ! 9ove/e8t returns true it kno's that there is
some data to %e read and it calls the propert" Current to access this data. #rom Current the &et accessor
&ets called 'hich al'a"s returns ^hi_ in our case. -hen 9ove/e8t &ets called and i it returns alse$
'e (uit out o the oreach statement. As 9ove/e8t al'a"s returns true$ 'e &o into an indeinite loop.
a.cs
2sin; System.Collections;
2blic class zzz
{
2blic static void Main()
{
yyy 3 + ne8 yyy();
3oreac9 (strin; i in 3)
{
System.Console.WriteLine(i);
}
}
}
class yyy
243884333.doc 2+4 od 221
{
2blic "Bn2merator LetBn2merator()
{
ret2rn ne8 ???();
}
}
class ??? = "Bn2merator
{
2blic strin; DE a + ne8 strin;D,E {Q9iR ) QbyeR )RnoR};
2blic int i + P';
2blic bool MoveJe?t()
{
i--;
System.Console.WriteLine(QMoveJe?tR - i);
i3 ( i ++ ,)
ret2rn 3alse;
else
ret2rn tr2e;
}
2blic void &eset()
{
System.Console.WriteLine(Q&esetR);
}
2blic ob4ect C2rrent
{
;et
{
System.Console.WriteLine(QC2rrent Q - aDiE);
ret2rn aDiE;
}
}
}
:utput
Mo%eFe/t0
Current hi
hi
Mo%eFe/t&
Current =(e
=(e
Mo%eFe/t
Current no
no
Mo%eFe/t5
<e have created an arra" a 'hich has 3 mem%ers and initialiKed them respectivel" to hi$ %"e and no %"
&ivin& the strin&s in QR immediatel" ater the ne'. 0ach time 9ove/e8t &ets called the varia%le i is
increased %" 1. ! the value o i is 3$ 'e have no more strin&s to return and thus 'e return alse$ else
'e return true. -he varia%le i keeps track o ho' man" times the unction 9ove/e8t is %ein& called.
As 9ove/e8t returns true$ Current &ets called 'hich returns a strin& rom the arra" usin& i as the
oset. -hus 'e can iterate throu&h the entire arra" dependin& upon the len&th.
a.cs
2sin; System.Collections;
2blic class zzz
{
2blic static void Main()
{
yyy 3 + ne8 yyy(QG9is is LreatR);
243884333.doc 2+E od 221
3oreac9 (strin; i in 3)
{
System.Console.WriteLine(i);
}
}
}
class yyy
{
strin; t;
2blic yyy(strin; t')
{
t + t';
}
2blic "Bn2merator LetBn2merator()
{
ret2rn ne8 ???(t);
}
}
class ??? = "Bn2merator
{
2blic strin; DE a;
2blic ???(strin; t,)
{
c9ar DE b + ne8 c9arD'E;
bD(E + \ \;
a + t,.Slit(b);
}
2blic int i + P';
2blic bool MoveJe?t()
{
i--;
System.Console.WriteLine(QMoveJe?t Q - i);
i3 ( i ++ a.Len;t9)
ret2rn 3alse;
else
ret2rn tr2e;
}
2blic void &eset()
{
System.Console.WriteLine(Q&esetR);
}
2blic ob4ect C2rrent
{
;et
{
System.Console.WriteLine(QC2rrent Q - aDiE);
ret2rn aDiE;
}
}
}
:utput
Mo%eFe/t 0
Current 6his
6his
Mo%eFe/t &
Current is
is
Mo%eFe/t
Current Qreat
243884333.doc 2+L od 221
Qreat
Mo%eFe/t 5
2rett" %i& pro&ram. At the time o creatin& a """ o%*ect 'e are passin& a strin& to the
constructor. -hus the """ constructor &ets called irst. -he constructor stores this strin& in
varia%le t. -he oreach statement calls @et0numerator 'hich no' creates a 888 o%*ect passin&
it the strin& throu&h t. -he constructor o 888 no' &ets called. 0ver" strin& class has a
mem%er unction called Split. Split 'ill %reak up a strin& on certain characters 'hich 'e call
delimiters. !n this case$ 'e 'ant our strin& to %e %roken up 'henever 'e encounter a space.
-he Split unction re(uires an arra" o chars 'hich it can use as a delimiter. -he reason it
re(uires an arra" is %ecause 'e ma" have more than one char that 'e 'ould like to %reak the
strin& on. Hike earlier$ the arra" a no' contains the arra" o strin&s. -he last chan&e is the
condition in the i statement. 0arlier 'e used a constant num%er$ no' 'e use a mem%er$
Hen&th$ o an arra" 'hich stores the len&th o the arra" or the num%er o mem%ers. -hus the
class """ can no' %e used as a collection class 'hich enumerates the individual 'ords in the
strin&. -he unction 1eset or some reason never ever &ets called.
14
Attri%utes$ -he 1election A2! And Conditionals
Attributes
a.cs
class zzz
{
2blic static void Main()
{
}
}
Dvi4ayE
class yyy
{
}
Compiler 1rror
a.cs(72): error C,0"A: 6he t(pe or namespace name 7%iEa(7 could not =e found (are (ou
missin) a usin) directi%e or an assem=l( referenceG)
An"thin& in a s(uare %racket is called an attri%ute. <e tried to create an attri%ute called vi*a"$ 'hich
CB$ or some reason$ does not seem to reco&niKe.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay = System.#ttrib2te
243884333.doc 2+P od 221
{
}
Dvi4ayE
class yyy
{
}
All that 'e have done is created a class vi*a" that has %een derived rom the class S"stem.Attri%ute
and the error simpl" disappears. -hus an attri%ute is simpl" a class that derives rom S"stem.Attri%ute.
-o understand attri%utes lets take an e8ample 'ith structures.
a.cs
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.i + 5..,5-.'*-,;
System.Console.WriteLine(a.i - " " - a.4 - " " - a.<);
}
}
str2ct yyy {
2blic int i;
2blic s9ort 4;
2blic byte <;
}
:utput
AA0!& 0 0
A simple revision once a&ain. <e have created a structure a$ that looks like """ and initialiKed onl"
one mem%er i. 3ence 'e see the 'arnin&s. -he other mem%ers * and k &et a deault value o Kero.
a.cs
2sin; System;
class zzz
{
2nsa3e 2blic static void Main()
{
Console.WriteLine(sizeo3(byte) - " " - sizeo3(s9ort) - " " - sizeo3(int) - " " -
sizeo3(lon;));
}
}
>csc a.cs
Compiler 1rror
a.cs("27): error C,07: Cnsafe code ma( onl( appear if compilin) @ith Nunsafe
-he error here sa"s that "ou have to use the Nunsae option 'hile compilin& an" unsae code.
>csc a.cs Nunsafe
:utput
& " 3
<e shall e8plain the modiier unsae in the ne8t chapter. SiKeo tells us ho' much memor" CB
allocates or a data t"pe. A %"te is allocated one memor" location$ short 2$ int 4 and a lon& 8.
243884333.doc 2+8 od 221
a.cs
2sin; System.&2ntime."nteroServices;
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.i + 5..,5-.'*-,;
System.Console.WriteLine(a.i - Q Q - a.4 - Q Q - a.<);
}
}
DStr2ctLayo2t(Layo2tSind.B?licit)E
str2ct yyy
{
D:ield@Zset(()E 2blic int i;
D:ield@Zset(()E 2blic s9ort 4;
D:ield@Zset(()E 2blic byte <;
}
:utput
AA0!& !&! 5
<e are usin& an attri%ute StructHa"out that %elon&s to the namespace
S"stem.1untime.!nteropServices. !n the earlier pro&ram$ 'e had used an attri%ute called vi*a". -hus$
StructHa"out is a class derived rom Attri%ute. <e are passin& a parameter Ha"outOind.08plicit to it.
-he output no' diers dramaticall".
0ver" varia%le is stored in memor". #ield.set indicates the startin& position o the varia%le 'ithin
the memor" location. .set o + 'ill position i$ *$ and k$ all three varia%les at the same memor"
address o a. 08plicit re(uires #ield.set to %e mentioned as 'e are e8plicitl" la"in& the order or the
varia%les held in the strucuture.Ha"outOind.Se(uential and Ha"outOind.Auto &ives dierent memor"
locations to each o the varia%le.
<e 'ill e8plain the reasons a little later in the comin& chapter 4;nsae Code7. <e have seen ho'
important attri%utes are so lets delve deeper into them.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay#ttrib2te = System.#ttrib2te
{
}
Dvi4ayE
class yyy
{
}
Dvi4ay#ttrib2teE
class yyy'
{
}
<e are allo'ed a little lee'a" in the name o the attri%ute. B" convention$ the attri%ute class should
end 'ith the 'ord Attri%ute and 'hen 'e use the attri%ute$ the name attri%ute is optional.
243884333.doc 2+D od 221
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay = System.#ttrib2te
{
}
Dvi4ay("9i")E
class yyy
{
}
Compiler 1rror
a.cs(&02): error C,&!0&: Fo o%erload for method 7%iEa(7 taDes 7&7 ar)uments
<e had used the attri%ute StructHa"out earlier 'here 'e passed a parameter. <hen 'e do the same
thin& 'ith our attri%ute vi*a"$ 'e &et the a%ove error.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s)
{
}
}
Dvi4ay("9i")E
class yyy
{
}
<e or&ot to add a constructor that accepts a strin& as a parameter. ! 'e had passed a num%er to our
attri%ute vi*a"$ 'e 'ould have to create a constructor that accepts an int. -hus i 'e pass 2 parameters
to vi*a"$ 'e need the appropriate constructor.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s )int i)
{
}
}
Dvi4ay("9i")'()m2<9i + *(()E
243884333.doc 21+ od 221
class yyy
{
}
Compiler 1rror
a.cs(&52&A): error C,0&05: 6he name 7muDhi7 does not e/ist in the class or namespace 7%iEa(7
<hat 'e tried to do is$ take a 'ord called mukhi and initialiKe it to 2++. CB comes %ack and tells us
that it does not kno' 'hat mukhi is.
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s )int i)
{
}
2blic int m2<9i;
}
Dvi4ay("9i")'()m2<9i + *(()E
class yyy
{
}
mukhi$ no'$ is called a named parameter. !t can also %e termed as a propert".
a.cs
class zzz
{
2blic static void Main()
{
}
}
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s )int i)
{
}
2blic int m2<9i;
2blic strin; sonal
{
;et
{
ret2rn "ss";
}
set
{
;
}
}
}
Dvi4ay("9i")'() m2<9i + *(() sonal + "bye")E
class yyy
{
243884333.doc 211 od 221
}
A named parameter is a non6static ield or a non6readonl" propert". A positional parameter is 'hat 'e
pass on to a constructor. <e have 2 positional parameters as our constructor has t'o parameters and
mukhi and sonal are our named parameters. -he named parameters come ater the positional ones. -he
positional parameter:s order is important$ %ut the named parameters can %e in an" order. ! 'e don:t
ollo' this rule 'e 'ill &et an error as ollo's.
Compiler 1rror
a.cs(&92): error C,&0&A: Famed attri=ute ar)ument e/pected
<hen 'e place the attri%ute %eore a unction$ the error disappears.
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
class zzz
{
2blic static void Main()
{
}
}
D#ttrib2teUsa;e(#ttrib2teGar;ets.Class)E
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s )int i)
{
}
2blic int m2<9i;
2blic strin; sonal
{
;et { ret2rn "ss"; }
set { ; }
}
}
class yyy
{
Dvi4ay("9i")'() sonal + "bye")m2<9i + *(( )E
2blic void abc() {}
}
Compiler 1rror
a.cs("2): error C,0!9: +ttri=ute 7%iEa(7 is not %alid on this declaration t(pe. >t is %alid on
7class7 declarations onl(.
Attri%ute;sa&e is one more attri%ute class derived rom Attri%ute. !t &ives us the option to decide
'here the user can use the Attri%ute. -he parameter in this case is class and hence 'e can use it onl" in
ront o a class and not in ront o a method. -he deault is an"'here.
3he 4e)!ection A0I
1election or !ntrospection is 'hen "ou look 'ithin to ind out a%out "our true sel. !n the same 'a"
'e need a method %" means o 'hich$ our pro&ram can ind out all a%out a class. <e need to kno'
ho' man" methods$ properties etc 'hile our pro&ram is e8ecutin& or runnin&. -his distinction is
important and 'e could al'a"s read the documentation i 'e 'anted to kno' more a%out the
unctionalit" o a class. But$ CB &ives us a lar&e num%er o unctions that tell us the innards o a class.
243884333.doc 212 od 221
-hese unctions put toðer have to %e used in a certain 'a". -he unctions have to %e called in a
certain order and the parameters to them have to conorm to certain data t"pes. -his concept is called
an A2! or a Application 2ro&ram !nterace. !n short$ an A2! is ho' a pro&rammer uses unctions to &et
a desired result.
a.cs
2sin; System;
class zzz
{
2blic static void Main()
{
Gye m;
m + tyeo3(int);
System.Console.WriteLine(m.Jame - " " - m.:2llJame);
m + tyeo3(System."nt,*);
System.Console.WriteLine(m.Jame - " " - m.:2llJame);
m + tyeo3(yyy);
System.Console.WriteLine(m.Jame - " " - m.:2llJame);
}
}
class yyy
{
}
:utput
>nt5 ,(stem.>nt5
>nt5 ,(stem.>nt5
((( (((
-"peo is a ke"'ord. !t needs a class name as a parameter. !n the irst case$ 'e are speci"in& a class
called int. t"peo returns an o%*ect that looks like -"pe. -his class has t'o mem%ers /ame$ 'hich
&ives the name o the class and #ull/ame 'hich is the name preceded 'ith the name o the
/amespace. <hen 'e use int as the name o the class$ the mem%er /ame does not displa" int %ut
!nt32M 'e mentioned earlier int is an alias or a structure !nt32 in the S"stem namespace. -his is 'hat
#ull/ame tells us. <e thus have visi%le proo that int is an alias or a structure. """ is class %elon&in&
to no namespace and hence the /ame and #ull/ame mem%ers are similar.
a.cs
2sin; System;
2sin; System.&e]ection;
class zzz
{
2blic static void Main()
{
Gye m + tyeo3(yyy);
Member"n3o DE n;
n + m.LetMembers();
Console.WriteLine(n.Len;t9);
3oreac9 ( Member"n3o a in n)
{
Console.WriteLine(a.Jame);
}
}
}
class yyy {
2blic void abc() {}
rivate int !r( int i ) { ret2rn (;}
243884333.doc 213 od 221
rotected strin; ?yz (strin; ; ) int ) {ret2rn "";}
}
:utput
A
Qet;ashCode
1Huals
6o,trin)
a=c
Qet6(pe
.ctor
<e are no' displa"in& the mem%ers o a class """. -he class -"pe has a unction called @et9em%ers
that returns an arra" o t"pe 9em%er!no. 0ver" arra" has a ield called Hen&th that returns the siKe o
the arra". !n our speciic case it is L. <e then use a oreach to run throu&h each mem%er o the
9em%er!no arra" and are displa"in& the name o each unction usin& the ield /ame rom the class
9em%er!no.
a.cs
2sin; System;
2sin; System.&e]ection;
class zzz
{
2blic static void Main()
{
Gye m + tyeo3(yyy);
Member"n3o DE n;
n + m.LetMembers();
Console.WriteLine(n.Len;t9);
3oreac9 ( Member"n3o a in n)
{
Console.WriteLine((Member"n3o)a - " " - a.Aeclarin;Gye);
}
}
}
class yyy {
2blic int i;
2blic void abc() {}
2blic int !r( int i ) { ret2rn (;}
2blic strin; ?yz (strin; ; ) int ) {ret2rn "";}
}
:utput
9
>nt5 i (((
>nt5 Qet;ashCode() ,(stem.:=Eect
<oolean 1Huals(,(stem.:=Eect) ,(stem.:=Eect
,(stem.,trin) 6o,trin)() ,(stem.:=Eect
Void a=c() (((
>nt5 pHr(>nt5) (((
,(stem.,trin) /(9(,(stem.,trin)2 >nt5) (((
,(stem.6(pe Qet6(pe() ,(stem.:=Eect
Void .ctor() (((
-he irst concept "ou need to %e clear 'ith is that 'e can inspect onl" details o pu%lic mem%ers and
protected or private like p(r and 8"K. Also varia%les are part o the mem%ers o a class. -he
9em%er!no o%*ect has a -oStrin& unction that displa"s the entire unction in all its &lor" includin&
parameters and their data t"pes. -he names o the parameter varia%les are ho'ever not %ein&
displa"ed. -he >eclarin&-"pe mem%er returns the class name that the mem%er %elon&s to. -hus 'e
can dierentiate 'hich class created the unction.
243884333.doc 214 od 221
Het us no' displa" the attri%utes used on a class.
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
2sin; System.&e]ection;
class zzz
{
2blic static void Main()
{
Gye m;
m + tyeo3(yyy);
System.Console.WriteLine(m.Jame);
3oreac9(ob4ect a in m.LetC2stom#ttrib2tes (tr2e))
Console.WriteLine(a);
}
}
D#ttrib2teUsa;e(#ttrib2teGar;ets.#ll)E
class vi4ay = System.#ttrib2te
{
strin; s')s*;int i';
2blic int m2<9i;
2blic override strin; GoStrin;()
{
ret2rn s'-" " - s*-" " - i' - " " - m2<9i;
}
2blic vi4ay(strin; s )int i)
{
s'+s;i'+i;
}
2blic strin; sonal
{
;et { ret2rn s*; }
set { s* + val2e; }
}
}
Dvi4ay("9i'")'() sonal + "bye'")m2<9i + *(( )E
class yyy
{
Dvi4ay("9i*")'(() sonal + "bye*")m2<9i + *((( )E
2blic void abc() {}
Dvi4ay("9i,")'((() sonal + "bye,")m2<9i + * )E
2blic int i;
}
:utput
(((
hi& =(e& &0 00
@etCustomAttri%utes takes a %oolean as parameter and returns an arra" o o%*ects. -he -oStrin&
unction o the attri%ute class &ets called 'hich 'ill decide 'hat strin& the attri%ute stands or.
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
2sin; System.&e]ection;
class zzz
{
2blic static void Main()
243884333.doc 21E od 221
{
Gye m;
m + tyeo3(yyy);
System.Console.WriteLine(m.Jame);
3oreac9(Met9od"n3o a in m.LetMet9ods())
{
ob4ect DE b + a.LetC2stom#ttrib2tes(tr2e);
3oreac9(#ttrib2te c in b)
{
Console.WriteLine(c);
}
}
}
}
D#ttrib2teUsa;e(#ttrib2teGar;ets.#ll)E
class vi4ay = System.#ttrib2te
{
strin; s')s*;int i';
2blic int m2<9i;
2blic override strin; GoStrin;()
{
ret2rn s'-" " - s*-" " - i' - " " - m2<9i;
}
2blic vi4ay(strin; s )int i)
{
s'+s;i'+i;
}
2blic strin; sonal
{
;et { ret2rn s*; }
set { s* + val2e; }
}
}
Dvi4ay("9i'")'() sonal + "bye'")m2<9i + *(( )E
class yyy
{
Dvi4ay("9i*")'(() sonal + "bye*")m2<9i + *((( )E
2blic void abc() {}
Dvi4ay("9i,")'((() sonal + "bye,")m2<9i + * )E
2blic void !r() {}
}
:utput
(((
hi =(e &00 000
hi5 =(e5 &000
-he o%*ect m looks like -"pe. As e8plained earlier$ 'e are callin& a unction called @et9ethods 'hich
returns an arra" o 9ethod!no:s. a loops throu&h each one. <e have t'o methods and the oreach &ets
e8ecuted t'ice. .nce or a%c and then or p(r. -he @etCustomAttri%utes also e8ists in a 9ethod!no
class that returns an arra" o o%*ects representin& our attri%utes. <e iterate throu&h each$ displa"in&
'hat the -oStrin& unction returns. As 'e have onl" one attri%ute per unction$ the second or each
&ets e8ecuted onl" once.
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
2sin; System.&e]ection;
class zzz
243884333.doc 21L od 221
{
2blic static void Main()
{
Gye m;
m + tyeo3(yyy);
System.Console.WriteLine(m.Jame);
3oreac9(Met9od"n3o a in m.LetMet9ods())
{
ob4ect DE b + a.LetC2stom#ttrib2tes(tr2e);
3oreac9(#ttrib2te c in b)
{
i3 ( c is vi4ay )
Console.WriteLine(c);
}
}
}
}
D#ttrib2teUsa;e(#ttrib2teGar;ets.#ll)E
class vi4ay = System.#ttrib2te
{
strin; s')s*;int i';
2blic int m2<9i;
2blic override strin; GoStrin;()
{
ret2rn s'-" " - s*-" " - i' - " " - m2<9i;
}
2blic vi4ay(strin; s )int i)
{
s'+s;i'+i;
}
2blic strin; sonal
{
;et { ret2rn s*; }
set { s* + val2e; }
}
}
Dvi4ay("9i'")'() sonal + "bye'")m2<9i + *(( )E
class yyy
{
Dvi4ay("9i*")'(() sonal + "bye*")m2<9i + *((( )E
2blic void abc() {}
Dvi4ay("9i,")'((() sonal + "bye,")m2<9i + * )E
2blic void !r() {}
}
-here is no chan&e at all in the output. A unction can %e decorated 'ith as man" attri%utes as "ou like.
<e 'ould like to ilter out certain attri%utes.
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
2sin; System.&e]ection;
class zzz
{
2blic static void Main()
{
Gye m;
m + tyeo3(yyy);
System.Console.WriteLine(m.Jame);
243884333.doc 21P od 221
3oreac9(Met9od"n3o a in m.LetMet9ods())
{
ob4ect DE b + a.LetC2stom#ttrib2tes(tr2e);
3oreac9(#ttrib2te c in b)
{
i3 ( c is vi4ay )
Console.WriteLine(c);
}
}
}
}
class vi4ay = System.#ttrib2te
{
2blic override strin; GoStrin;()
{
ret2rn "vi4ay";
}
}
class vi4ay' = System.#ttrib2te
{
2blic override strin; GoStrin;()
{
ret2rn "vi4ay";
}
}
class yyy
{
Dvi4ay()E
2blic void abc() {}
Dvi4ay()E
Dvi4ay'()E
2blic void !r() {}
}
:utput
(((
%iEa(
%iEa(
<e have t'o attri%ute classes vi*a" and vi*a"1. -he unction p(r has %een decorated 'ith 2 attri%utes
'hereas a%c 'ith onl" one. 3o'ever 'e do not see vi*a"1 in the output as the :c is vi*a": makes the i
statement true onl" or the attri%ute vi*a" and not vi*a"1. #or the unction p(r @etCustomAttri%utes
returns an arra" o siKe t'o$ %ut the i statement is true onl" or one o them$ the one 'ith the attri%ute
name vi*a". -his is %ecause o the :is:.
a.cs
2sin; System;
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
i3 ( a is yyy)
Console.WriteLine("a yyy");
??? b + ne8 yyy();
i3 ( b is ???)
Console.WriteLine("b ???");
i3 ( b is yyy)
Console.WriteLine("b yyy");
243884333.doc 218 od 221
int d + '(;
i3 ( d is yyy)
Console.WriteLine("b yyy");
}
}
class ???
{
}
class yyy = ???
{
}
:utput
a (((
= ///
= (((
<e 'ould like to kno' the data t"pe o an o%*ect at runtime. CB oers "ou a ke"'ord :is: that lets "ou
check the data t"pe o an o%*ect. a looks like """ and :is: results in true. B looks like 888 %ut is
initialiKed to a ne' """. -hus it dou%les up or a """ and a 888 resultin& in the ne8t t'o is:s returnin&
true. > is an int and not a """$ so the last :is: is alse.
Attributes 4e'isited
2ositional parameters are a must 'hereas names parameters are optional. Attri%ute parameters can %e a
%ool$ %"te$ char$ short$ int$ lon&$ loat and dou%le. -hese are the simple t"pes that CB supports. .ther
data t"pes are strin&$ enums$ o%*ects arra"s etc.
Attri%ute usa&e has a position parameter 'hich speciies the elements 'here the attri%ute can %e used.
-he deault is All. !t also has one named parameter called Allo'9ultiple.
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
class zzz
{
2blic static void Main()
{
}
}
D#ttrib2teUsa;e(#ttrib2teGar;ets.#ll)E
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s)
{
}
}
class yyy
{
Dvi4ay("9i")EDvi4ay("9i'")E
2blic void abc() {}
}
Compiler 1rror
a.cs(&32&!): error C,0!79: Iuplicate 7%iEa(7 attri=ute
243884333.doc 21D od 221
B" deault 'e cannot use the same attri%ute t'ice on an" entit".
a.cs
2sin; System.&2ntime."nteroServices;
2sin; System;
class zzz
{
2blic static void Main()
{
}
}
D#ttrib2teUsa;e(#ttrib2teGar;ets.#ll)#llo8M2ltile+tr2e)E
class vi4ay = System.#ttrib2te
{
2blic vi4ay(strin; s)
{
}
}
class yyy
{
Dvi4ay("9i")EDvi4ay("9i'")E
Dvi4ay("9i*") ) vi4ay("9i,")E
2blic void abc() {}
}
<e &et no error as %" deault the Allo'9ultiple named parameter has a value o alse. ! 'e set its
value to true$ 'e are allo'ed to use multiple attri%utes on an" entit". -he a%ove t'o orms are similar
and either one can %e used. Attri%ute permits us to set declarative inormation or various pro&ram
entities or use %" someone else at run time.
Conditiona!s
a.cs
2sin; System.Aia;nostics;
2sin; System;
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.abc();
}
}
class yyy
{
DConditional("vi4ay")E
2blic void abc()
{
Console.WriteLine("abc");
}
}
<hen 'e run the a%ove pro&ram 'e &et no output at all. !n other 'ords the unction a%c does not &et
called at all. -his is inspite o 'ritin& a.a%c().
a.cs
YdeWne vi4ay
2sin; System.Aia;nostics;
243884333.doc 22+ od 221
2sin; System;
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.abc();
}
}
class yyy
{
DConditional("vi4ay")E
2blic void abc()
{
Console.WriteLine("abc");
}
}
:utput
a=c
An" line %e&innin& 'ith a B is read %" the CB pre6processor$ a pro&ram that starts %eore the CB
compiler starts. !t has 'ords like Bdeine 'hich creates a varia%le or 'ord called vi*a". !n a
pro&rammin& lan&ua&e$ a varia%le has to have a value$ %ut in the preprocessor scheme o thin&s$ it
ma"Nma"not have a value. 3o'ever i 'e do not &ive it a value$ like in this case$ the varia%le is onl"
set to have %een deined or created. An"thin& in WX %rackets is an Attri%ute class. 0arlier 'e had not
created a varia%le vi*a" and hence the entire code o a%c 'as let out o the e8ecuta%le ile. /ot onl"
that$ %ut all calls to unction a%c 'ere eliminated rom our code. All o this %" deinin& or not deinin&
a varia%le vi*a". -his is 'hat 'e passed as the attri%ute to Conditional. <e can create unctions that are
omitted durin& compilation dependin& upon a preprocessin& s"m%ol.
<hen 'e 'rite code$ 'e add a lot o code or de%u&&in& purposes. -his code is to help the
pro&rammer de%u& code. Ater a unction 'orks$ it is error ree$ 'e do not re(uire an" o this
de%u&&in& code. .ne 'a" to eliminate this de%u&&in& code is %" makin& the unctions conditional.
-he resultin& code is called a :1etail %uild: and the de%u&&in& version$ o%viousl" a :>e%u& %uild:. A
1etail %uild is much smaller in siKe and o%viousl" much aster. -he Bdeine has to %e at the start o
code.
Another 'a" o achievin& the same result is %" eliminatin& the Bdeine rom the code and creatin& a
preprocessor s"m%ol as an option to the compiler.
>csc a.cs Nd:%iEa(
-he compiler option is Nd and the colon is part o the s"nta8. #ollo'in& the colon is the name o the
preprocessor s"m%ol. !n this case$ it is vi*a". <e7ve discussed preprocessors in one o the earlier
chapters.
a.cs
2sin; System;
class zzz
{
2blic static void Main()
{
yyy a + ne8 yyy();
a.abc();
}
}
class yyy
243884333.doc 221 od 221
{
D@bsoleteE
2blic void abc()
{
Console.WriteLine("abc");
}
}
Compiler 1rror
a.cs(72&): @arnin) C,0A&: 7(((.a=c()7 is o=solete
:utput
a=c
9an" a times 'e create unctions in a class 'hich 'e 'ould not 'ant the user to use$ as these
unctions 'ere useul "ears a&o$ %ut are no' o%solete. -he onl" 'a" to 'arn the user that
some time in the uture 'e 'ill no lon&er support these unctions is %" markin& them 'ith the
attri%ute .%solete. <e see the 'arnin& as displa"ed a%ove %ut the pro&ram runs as normal.