You are on page 1of 25

Mai

n()andCommand
-Li
neAr
gument
s(C#Pr
ogr
ammi
ng
Gui
de)
TheMainmet hodistheentr
yp oi
ntofaC#c ons
oleap
pli
cati
onorwind
owsappl
ic
ati
on.(
Lib
rariesand
ser
vicesdonotr equi
reaMai nmethodasanent
rypoi
nt.)
.Whentheappl
ic
ati
oniss
tart
ed,theMain
methodisthefirstmethodthati
sinvoked
.

Therec
anonl ybeoneentrypoi
ntinaC#p rogr
am.Ify ouhavemorethanonecl
assthathasaMai
nmethod
,
youmustcomp i
ley
ourp r
ogramwi t
ht he/maincomp
ileropti
ontospec
ifywhichMai
nmet hodt
ouseast
he
entr
ypoint.Formoreinfor
mation,see/main(C#Comp il
erOpti
ons
).

c
lassTes tCl
ass
{
s
tat i
cv oi
dMai n(
stri
ng[]args)
{
//Displ
ayt henumberofc ommandlineargument
s:
System.Consol
e.Writ
eLine(ar
gs.Length)
;
}
}

Ov
erv
iew

 TheMai nmet hodi stheent ryp ointofan. exep rogram;i tiswheret hep rogramc ont rolst
artsand
ends.
 Mai ni sd ecl
ar edinsid
eac lassors truc t
.Mai nmus tb es tati
candi tshouldnotb ep ub li
c.(I
nthe
earli
erexamp le,itreceivest hed efaultac cessofp riv
at e.)Theenclosingc l
assors truc tisnot
requiredt ob es t
atic.
 Mai nc anei therhav eav oidori ntretur nt y
p e.
 TheMai nmet hodc anb ed eclar edwithorwi thoutas tring[]paramet erthatc ontai nsc ommand-
l
inear gument s.Whenus ingVi s ualStud iotoc reateWi ndowsFor msap p l
ic
at i
ons,y ouc anaddthe
paramet ermanual l
yorel seus et heEnv ironmentc l
asst oobtainthec ommand -linear guments.
Paramet er sarer eadaszer o-ind exedc ommand -l
inear gument s
.UnlikeCandC++,t henameoft he
programi snott reatedast hef irstcommand -lineargument .

C#Compi
lerOpt
ionsLi
stedAl
phab
eti
cal
ly
Thefol
l
owingc ompi
lerop
tionsar
esor
tedal
phab
eti
cal
ly
.Forac
ategor
icall
is
t,s
eeC#Comp
ilerOp
tions
Li
stedbyCategory
.

Op
tion Pur
pos
e

@ Read
sar
esp
ons
efi
lef
ormor
eop
tions
.

/
? Di
spl
aysaus
agemes
saget
ost
dout
.

/
add
mod
ule Li
nkst
hes
pec
ifi
edmod
ulesi
ntot
hisas
semb
ly

/
app
conf
ig Sp
eci
fiest
hel
ocat
ionofap
p.c
onf
igatas
semb
lyb
ind
ingt
ime.

/
bas
ead
dres
s Sp
eci
fiest
heb
asead
dres
sfort
hel
ibr
aryt
obeb
uil
t.
/
bugr
epor
t Cr
eat
esa'
BugRep
ort
'fi
le.Thi
sfi
lewi
llb
esentt
oget
herwi
thanyc
ras
hinf
ormat
ioni
f
i
tisus
edwi
th/
err
orr
epor
t:pr
omptor/
err
orr
epor
t:s
end
.

/
chec
ked Caus
est
hec
omp
ilert
ogener
ateov
erf
lowc
hec
ks.

/
cod
epage Sp
eci
fiest
hec
odep
aget
ous
ewhenop
eni
ngs
our
cef
il
es.

/
deb
ug Emi
tsd
ebuggi
ngi
nfor
mat
ion.

/
def
ine Def
inesc
ond
iti
onalc
omp
ilat
ions
ymb
ols
.

/
del
ays
ign Del
ay-s
ignst
heas
semb
lyb
yus
ingonl
ythep
ubl
icp
artoft
hes
trongnamekey
.

/
doc Sp
eci
fiesanXMLDoc
ument
ati
onf
il
etogener
ate.

/
err
orr
epor
t Sp
eci
fieshowt
ohand
lei
nter
nalc
omp
ilerer
ror
s:p
romp
t,s
end
,ornone.Thed
efaul
tis
none.

/
fil
eal
ign Sp
eci
fiest
heal
ignmentus
edf
orout
putf
il
esec
tions
.

/
ful
lp
aths Caus
est
hec
omp
ilert
ogener
atef
ull
yqual
if
iedp
aths
.

/
hel
p Di
spl
aysaus
agemes
saget
ost
dout
.

/
inc
rement
al Enab
lesi
ncr
ement
alc
omp
ilat
ion[
obs
olet
e].

/
key
cont
ainer Sp
eci
fiesas
trongnamekeyc
ont
ainer
.

/
key
fil
e Sp
eci
fiesas
trongnamekeyf
il
e.

/
langv
ers
ion Sp
eci
fiesl
anguagev
ers
ionmod
es:I
SO-1orDef
aul
t.

/
li
b Sp
eci
fiesad
dit
ionald
irec
tor
iesi
nwhi
cht
osear
chf
orr
efer
enc
es.

/
li
nk MakesCOMt
ypei
nfor
mat
ioni
nsp
eci
fiedas
semb
liesav
ail
abl
etot
hep
roj
ect
.

/
li
nkr
esour
ce Li
nkst
hes
pec
ifi
edr
esour
cet
othi
sas
semb
ly.

/
mai
n Sp
eci
fiest
het
ypet
hatc
ont
ainst
heent
ryp
oint(
ignor
eal
lot
herp
oss
ibl
eent
ryp
oint
s).

/
noc
onf
ig I
nst
ruc
tst
hec
omp
ilernott
oaut
oinc
lud
eCSC.
RSPf
il
e.

/
nol
ogo Sup
pres
sesc
omp
ilerc
opy
rightmes
sage.

/
nos
tdl
ib I
nst
ruc
tst
hec
omp
ilernott
oref
erenc
est
and
ardl
ibr
ary(
msc
orl
ib.
dll
).
/
nowar
n Di
sab
less
pec
ifi
cwar
ningmes
sages

/
nowi
n32mani
fe I
nst
ruc
tst
hec
omp
ilernott
oemb
edanap
pli
cat
ionmani
fes
tint
heexec
utab
lef
il
e.
s
t

/
opt
imi
ze Enab
les
/di
sab
lesop
timi
zat
ions
.

/
out Sp
eci
fiest
heout
putf
il
ename(
def
aul
t:b
asenameoff
il
ewi
thmai
ncl
assorf
irs
tfi
le)
.

/
pdb Sp
eci
fiest
hef
il
enameandl
ocat
ionoft
he.
pdbf
il
e.

/
plat
for
m Li
mit
swhi
chp
lat
for
mst
hisc
odec
anr
unon:x86,I
tani
um,x64,orany
cpu.Thed
efaul
tis
any
cpu.

/
rec
urs
e I
ncl
udesal
lfi
lesi
nthec
urr
entd
irec
tor
yands
ubd
irec
tor
iesac
cor
dingt
othewi
ldc
ard
s
pec
ifi
cat
ions
.

/
ref
erenc
e Ref
erenc
esmet
adat
afr
omt
hes
pec
ifi
edas
semb
lyf
il
es.

/
res
our
ce Emb
edst
hes
pec
ifi
edr
esour
ce.

/
tar
get Sp
eci
fiest
hef
ormatoft
heout
putf
il
ebyus
ingoneoff
ourop
tions
:/t
arget
:exe,
/
tar
get
:li
brar
y,/
tar
get
:mod
ule,/
tar
get
:wi
nexe.

/
uns
afe Al
lowsuns
afec
ode.

/
utf
8out
put Out
put
scomp
ilermes
sagesi
nUTF-8enc
odi
ng.

/
war
n Set
sthewar
ningl
evel(
0-4)
.

/
war
nas
err
or Rep
ort
ssp
eci
ficwar
ningsaser
ror
s.

/
win32i
con Us
est
hisi
conf
ort
heout
put
.

/
win32mani
f t Sp
es eci
fiesac
ust
omwi
n32mani
fes
tfi
le.

/
win32r
es Sp
eci
fiest
hewi
n32r
esour
cef
il
e(.
res
).

Types

 Types
,Var
iab
les
,andVal
ues
C#i sas t
r ongly-t
y p
edlanguage.Ev eryvari
ableandc ons
t anthasat ype,asd oeseveryexp ressi
ont hat
evaluatest oav al
ue.Everymethods i
gnaturespeci
f i
esat yp eforeachi nputp arameterandf ort heretur
n
val
ue.The. NETFr ameworkclassli
b rarydefi
nesas etofb uilt-i
nnumer icty p
esaswel lasmor ec omplex
typesthatr ep r
esentawi devari
etyofl ogic
alconstructs,suc hasthef ilesystem,net workconnec ti
ons,
col
lecti
onsandar raysofobjects,andd ates.Atypi
calC#p rogramus est ypesf r
omt heclassli
brar yaswell
asus er
-d efinedtypesthatmodelt heconceptsthatar espec i
f i
ctothep rogram' spr
ob l
emd omain.

Thei
nfor
mat
ions
tor
edi
nat
ypec
ani
ncl
udet
hef
oll
owi
ng:

 Thestoragespac
ethatav ar i
ableofthet yperequir
es.
 Themaximumandmi nimumv al
uest hatitcanrep r
esent.
 Thememb ers(
methods,fi
elds,events,ands oon)thatitcontai
ns.
 Thebaset y
peiti
nheritsfrom.
 Thel
oc ati
onwherethememor yf orvari
ab l
eswillbeall
ocatedatrunt
ime.
 Thekindsofoper
ationsthatar epermitted.

Thecomp i
lerusestypeinformati
ont omakesurethatalloperati
onsthatareperfor
medinyourcod
eare
typesafe.Forexample,ifyoudeclareavari
ableoftypeint
,t hecompil
eral
lowsyoutousethevari
abl
ein
addi
tionands ubt
racti
onop erat
ions.Ifyoutrytoperformt hos
es ameoper
ationsonavari
abl
eoftypebool
,
thecompil
ergener at
esaner ror,asshowninthefoll
owingexamp l
e:
i
nta=5;

i
ntb=a+2;/
/OK

b
oolt
est=t
rue;

/
/Er
ror
.Op
erat
or'
+'c
annotb
eap
pli
edt
oop
erand
soft
ype'
i
nt'
and'
bool
'
.

i
ntc=a+t
est
;

Not
e

CandC++d
evel
oper
s,not
icet
hati
nC#,b
ooli
snotc
onv
ert
ibl
etoi
nt.

Thecompil
erembedsthety
peinfor
mat
ioni
ntot
heexecutabl
efil
easmetad
ata.Thecommonlanguage
runti
me(CLR)usesthatmetad
ataatrunt
imet
ofurtherguaranteet
ypes
afetywhenital
locat
esand
recl
aimsmemory
.

Spec
ifyi
ngTypesi
nVar
iab
leDec
lar
ati
ons

Whenyoudecl
areavar
iabl
eorc onst
antinaprogram,youmusteit
hersp
ecif
yitstyp
eorusethev ar
keywor
dtoletthec
ompil
erinf
ert hetyp
e.Thefoll
owingexampl
eshowssomevari
abl
edec
lar
ationsthat
usebothb
uil
t-i
nnumeri
ct y
pesandc ompl
exuser-def
inedty
pes:

/
/Dec
lar
ati
ononl
y:

f
loatt
emp
erat
ure;
s
tri
ngname;

My
Clas
smy
Clas
s;

/
/Dec
lar
ati
onwi
thi
nit
ial
izer
s(f
ourexamp
les
):

c
harf
irs
tLet
ter='
C'
;

v
arl
imi
t=3;

i
nt[
]sour
ce={0,1,2,3,4,5}
;

v
arquer
y=f
romi
temi
nsour
ce

wher
eit
em<=l
imi
t

s
elec
tit
em;

Thety
p esofmethodp
arametersandretur
nv al
uesar
especi
fiedi
nthemethodsi
gnat
ure.Thef
oll
owi
ng
si
gnatureshowsamethodthatrequi
resanintasani
nputargumentandr
eturnsastr
ing:

p
ubl
ics
tri
ngGet
Name(
intI
D)

i
f(I
D<names
.Lengt
h)

r
etur
nnames
[ID]
;

el
se

r
etur
nSt
ring.
Emp
ty;

p
riv
ates
tri
ng[
]names={"
Spenc
er"
,"Sal
ly
","
Doug"}
;

Afterav ariab
leisdecl
ared,i
tc annotb ere-declaredwithanewt ype,anditcannotb eass i
gnedav al
ue
thatisnotc ompati
blewithit
sd ec l
aredtype.Forexamp l
e,y oucannotd ec
lareanintandt henassi
gni ta
Booleanvalueoft r
ue.Howev er,valuescanb econv er
tedt oot hertypes,forexamplewhent heyare
assi
gnedt onewv ariab
lesorp assedasmet hodar guments.At ypec onvers
ionthatd oesnotc ausedatalos
s
isperfor
medaut omat i
cal
lybyt hec ompi
ler
.Ac onv ersi
ont hatmi ghtcausedatalossr equi
resac as
ti nthe
sourcecode.

Formor
einf
ormat
ion,s
eeCas
tingandTy
peConv
ers
ions(
C#Pr
ogr
ammi
ngGui
de)
.

Bui
lt-i
nTypes
C#p rovi
desas tand ar
ds etofbuil
t-i
nnumer i
ct y
pest orepresentinteger
s,fl
oati
ngp ointvalues,Bool
ean
expressi
ons,textc haracters,dec
imalval
ues,andothert y
pesofd ata.Thereareals
ob uilt
-ins tr
ingand
objecttypes.Thes eareav ai
lab
leforyoutouseinanyC#p rogram.Foramor einformat i
onab outthebui
lt
-intypes,seeRef erenceTablesforTypes(C#Ref er
ence).

Cus
tomTypes

Youuset hestruct,clas s,i


nt er face,andenumc ons
t ructstocreatey ourownc ustomt y p
es .The.NET
Framewor kcl
asslibrar yitselfi sac oll
ecti
onofcustomt ypesprovid
edb yMicros oftthaty ouc anusei
nyour
ownap p
licati
ons.Byd efault,t hemos tf r
equentl
yus edtypesinthec l
as slib
r aryar eav ail
ab l
ei nanyC#
progr
am.Ot hersb ec
omeav ailableonlywheny ouexplici
tl
yad dap r
ojec trefer encet ot heas semblyi
nwhic
h
theyared efi
ned.Aft ert hec omp il
erhasar ef
erenc
et otheassembly,y oucand ecl
arev ariabl
es(and
const
ants )ofthet y
p esd eclar edint hatassembl
yins ourcecode.Formor einfor mation,s ee.NET
Framewor kClassLib
r ar y.

TheCommonTypeSys
tem

I
tisi
mpor
tantt
ound
ers
tandt
wof
und
ament
alp
oint
sab
outt
het
ypes
yst
emi
nthe.
NETFr
amewor
k:

 Its upportst hep rincipl


eofi nher i
tanc e.Ty pesc and er i
v efr omot hert ypes,c alledb as et ypes.The
deri
v edt yp
ei nher it
s( withs omer estric tions)themet hod s,pr op er ti
es,andot hermemb er softhe
baset ype.Theb aset ypecani nt urnd er ivef roms omeot hert y pe,i nwhi chc as et hed er i
v edt ype
i
nher it
st hememb ersofb othb aset ypesi nitsinher i
tanc ehier arc hy.Al ltypes ,i ncludingb uil
t-i
n
numer i
ct ypess uc hasSy stem. Int32( C#key word :int),d eriveul timat elyf romas ingleb as et ype,
whichisSy stem. Ob j
ect( C#key wor d:ob j ect).Thisuni f i
edt y
p ehi erarc hyi sc all
edt heCommonTy pe
System( CTS) .Formor einfor mationab outi nherit ancei nC#,s eeI nher itance( C#Pr ogr ammi ng
Gui
d e).
 Eac hty p
ei nt heCTSi sdef i
nedasei therav al
uet ypeorar ef er encet ype.Thi si nc l
ud esal lcustom
typ
esi nt he. NETFr amewor kc l
as sl
ib rar yandal s oy ourownus er -definedt yp es.Ty p
est haty ou
defi
neb yusingt hes tructkey wor dar ev aluet ypes ;alltheb ui l
t -innumer ict ypesar es tr ucts.
Typest haty oud ef i
neb yus i
ngt hec lasskey wor dar erefer enc et ypes.Ref er enc et ypesandv al
ue
typ
eshav ed i
f f
er entc omp i
le-timer ules ,andd i
ffer entr un-t imeb ehav ior.

Thef
oll
owi
ngi
ll
ust
rat
ions
howst
her
elat
ions
hipb
etweenv
aluet
ypesandr
efer
enc
ety
pesi
ntheCTS.

Val
uet
ypesandr
efer
enc
etypesi
ntheCTS
Not
e

Youc
ans
eet
hatt
hemos
tcommonl
yus
edt
ypesar
eal
lor
gani
zedi
ntheSy
stemnames
pac
e.Howev
er,t
he
names
pac
einwhi
chat
ypei
scont
ainedhasnor
elat
iont
owhet
heri
tisav
aluet
ypeorr
efer
enc
ety
pe.

Val
ueTypes

Val
uetypesderivefromSystem.ValueType,whic
hder i
vesfromSy stem.Ob
ject.Typesthatderiv
ef rom
Syst
em.Val
ueTy p
ehav espec
ialbehaviorintheCLR.Valuet y
pev ariabl
esdi
rectlycont
aintheirval
ues,
whic
hmeanst hatthememor yisall
ocatedinli
neinwhat ev
erc ontextthevari
ab l
eisdecl
ared.Thereisno
sep
arat
eheapal loc
at i
onorgarbagec ol
lecti
onoverheadforv al
ue-t y
pevari
ables.

Ther
ear
etwoc
ategor
iesofv
aluet
ypes
:st
ruc
tandenum.

Theb
uil
t-i
nnumer
ict
ypesar
est
ruc
ts,andt
heyhav
epr
oper
tiesandmet
hod
sthaty
ouc
anac
ces
s:

C#

/
/St
ati
cmet
hodont
ypeBy
te.

b
yteb=By
te.
MaxVal
ue;

Buty
oud
ecl
areandas
signv
aluest
othemasi
ftheywer
esi
mpl
enon-aggr
egat
ety
pes
:

b
ytenum=0xA;

i
nti=5;
c
harc='
Z';

Valuet yp
esar eseal
ed ,whic
hmeans ,f orexample,thaty ouc annotd eri
veatypef r
omSy stem.Int 32,and
youc annotd efineas truc
tt oinher
itf romanyus er-definedc las
sors tructb
ecauseas tructcanonl y
inheritfromSy s t
em.ValueType.Howev er,astructc animp l
ementoneormor einterfac
es.Youc anc asta
structtyp etoani nterfacetype;thisc esab
aus oxingoper ationt owrapthestructinsi
dear efer encetype
objectont hemanagedheap .Boxingop erati
onsoc c
urwheny oup assavaluetypetoamet hodt hatt akesa
System.Ob jectasani nputparameter .Formorei nformation,s eeBoxingandUnboxing(C#Pr ogr amming
Guide).

Youusethestruc
tkeywordt
oc r
eateyourowncustomv
aluety
pes.Typi
call
y,ast
ruc
tisus
edasa
cont
ainerforasmal
lsetofr
elatedv
ariab
les
,asshowninthef
oll
owingexampl
e:

p
ubl
ics
truc
tCoOr
ds

{ p
ubl
ici
ntx,y
;

p
ubl
icCoOr
ds(
intp
1,i
ntp
2)

x=p
1;

y=p
2;

Formor
einf
ormat
ionab
outs
truc
ts,s
eeSt
ruc
ts(
C#Pr
ogr
ammi
ngGui
de)
.Formor
einf
ormat
ionab
out
val
uet

t
ypesi
nthe.
NETFr
amewor
k,s
eeCommonTy
peSy
stem.

Theothercategoryofval
uet ypesi
senum.Anenumdefinesas etofnamedintegralconst
ants.For
example,t
heSy st
em.IO.
FileModeenumerat
ionint
he.NETFr ameworkclas
slib
r ar
yc ontai
nsas etofnamed
const
antintegersthatspecif
yhowaf il
eshoul
dbeop
ened .I
ti sdef
inedasshowni nthefoll
owingexampl
e:

p
ubl
icenumFi
leMod
e

Cr
eat
eNew=1,

Cr
eat
e=2,

Op
en=3,

Op
enOr
Creat
e=4,

Tr
unc
ate=5,

Ap
pend=6,

}
TheSystem.
IO.FileMod
e.Cr eateconstanthasav al
ueof2.Howev er,t
henameismuchmoremeani
ngf
ulfor
humansreadi
ngt hesourcec od
e,andf orthatreasoniti
sb et
t ertouseenumer
ati
onsi
nst
eadofcons
tant
l
iter
alnumbers.Formor einformation,seeSys
tem. I
O.Fi
leMode.

Al
lenumsinher
itfromSy
stem.Enum,whi
chinheri
tsfr
omSystem.
Val
ueTyp
e.Allt
herul
esthatapp
lyto
str
uctsal
soapplyt
oenums.Formoreinf
ormat i
onab
outenums,s
eeEnumerat
ionTy
pes(C#Programmi
ng
Guid
e).

Ref
erenc
eTy
pes
Atypethati
sdefi
nedasaclass
,delegate,array,ori
nter fac
eisareferencetype.Atr
unt i
me,wheny ou
dec
lareavar
iabl
eofareferenc
et ype,t
hev ariabl
econtainstheval
uenullunti
lyouexpl
ici
tl
yc reatean
i
nstanceoft
heobjectb
yusingthenewop er
ator,orassignitanobjectthathasbeencreatedelsewhere
byusi
ngnew,asshowninthefoll
owingexampl e:
C#

My
Clas
smc=newMy
Clas
s()
;

My
Clas
smc
2=mc
;

Ani
nterf
ac emustbeini
tial
izedt
ogetherwi
thacl
assob
jectthati
mpl
ement
sit.IfMyCl
assi
mpl
ement
s
IMy
Interface,youcr
eateani ns
t eofI
anc MyI
nterf
aceasshownint
hefol
lowi
ngexampl
e:

C#

I
MyI
nter
fac
eif
ace=newMy
Clas
s()
;

Whent heobjecti
screat ed
,t hememor yisal
locat
edont hemanagedheap,andt hevar i
ableholdsonlya
referencetotheloc
at i
onoft heobject
.Typesont hemanagedheaprequi
reover headb othwhent heyare
all
ocatedandwhent heyar ereclai
medb ytheautomaticmemorymanagementf unctionali
tyoft heCLR,
whichisknownasgar bagec ol
lecti
on.However,garbagecol
lecti
onisal
sohighl
yop timized,andinmos t
scenariosi
tdoesnotc reateap erformancei
s s
ue.Formorei nf
ormati
onaboutgar bagec oll
ecti
on,see
Automat i
cMemoryManagement .

Allarr
aysarereferencetyp
es ,evenifthei
relement
sarev
aluetypes
.Array
simpl
ici
tl
yderi
vefromthe
System.Ar
raycl
as s
,b uty
oud eclareandusethemwitht
hesimpl
if
iedsynt
axthati
sprovi
dedbyC#,as
showninthefoll
owingexample:

C#

/
/Dec
lar
eandi
nit
ial
izeanar
rayofi
nteger
s.

i
nt[
]nums={1,2,3,4,5}
;

/
/Ac
ces
sani
nst
anc
epr
oper
tyofSy
stem.
Arr
ay.
i
ntl
en=nums
.Lengt
h;

Ref er
enc ety
pesf ul
lysupportinheri
tance.Wheny oucreat
eac las
s,youcani nheri
tfromanyot her
i
nt erfaceorclas
st hatisnotd efi
nedass eal
ed,andotherclassescaninheritfromyourclas
sandov erri
de
yourv ir
tualmethods.Formor einformati
onab outhowt oc
reat eyourownc lasses
,seeClassesandStructs
(C#Pr ogrammingGuide).Formor einfor
mat i
onab outi
nheri
t anceandvirtualmethods,s
eeI nheri
tanc
e
(C#Pr ogrammingGuide).

TypesofLi
ter
alVal
ues

I
nC#,l it
eralvaluesr eceiveat yp
ef romthecompil
er.Youc ans pec i
fyhowanumer i
cliteralshoul
db etyped
b
yap pendi
ngal et tert ot heendoft henumber.Forexample,t osp eci
f ythatthev alue4.56s houl
dbe
t
reatedasaf l
oat ,ap pendan" f"or"F"afterthenumber:4 .56f.I fnol etterisappended ,thecompi
lerwill
i
nferat ypefort hel i
t eral.Formoreinformati
onaboutwhi cht y
p esc anb especif
iedwit hlettersuf
f i
xes
,
s
eet hereferencep agesf orindi
vidualtyp
esinValueTypes( C#Ref erence).

Becauseli
ter
alsaretyp
ed,andal
lty
pesd
eri
veul
ti
mat
elyf
romSy
stem.
Obj
ect
,youc
anwr
iteandc
omp
ile
cod
es uchasthefol
lowi
ng:

C#

s
tri
ngs="
Theans
weri
s"+5.
ToSt
ring(
);

/
/Out
put
s:"
Theans
weri
s5"

Cons
ole.
Wri
teLi
ne(
s);

Ty
pet
ype=12345.
Get
Typ
e()
;

/
/Out
put
s:"
Sys
tem.
Int
32"

Cons
ole.
Wri
teLi
ne(
typ
e);

Gener
icTypes

At ypecanbedec l
aredwi thoneormor etypeparametersthatserveasap laceholderfort heactualtype
(
t heconcret
et ype)t hatcl
ientcodewil
lprovid
ewheni tcreatesanins t
anceoft het y
p e.Sucht yp
esar e
caledgener
l ictypes.Forexamp l
e,the.NETFr ameworkt y
p eSyst
em. Col
lec
tions.Generic.
List<T>hasone
typep ar
ametert hatb yconvent
ionisgiv
ent henameT.Wheny oucreateani nstanceoft het yp
e,y ou
speci
f ythetyp
eoft heobjectsthattheli
stwillcont
ain,forexample,stri
ng:
C#

Li
st<s
tri
ng>s
tri
ngs=newLi
st<s
tri
ng>(
);

Theus eofthet y
pep arametermakesi tpossi
bletor eusethes ameclasstoholdanyt yp
eofel ement ,
withouthavingtoconv erteachelementtoobject.Gener i
cc ol
lect
ionclas
s esarecaleds
l t rongly-typed
col
lecti
onsbecauset hec ompi
lerknowsthes p
ec i
fictypeoft hecoll
ecti
on'selementsandc anr aiseaner ror
atc ompi
le-t
imeif,forexamp le,youtrytoaddani ntegert othes tr
ingsobjectinthep reviousexamp le.
Formor einfor
mat i
on,s eeGenerics(C#Programmi ngGuide).
I
mpl
ici
tTypes
,AnonymousTypes
,andNul
lab
leTypes

Asstatedprev
iousl
y,youcanimpli
citl
ytypealocalvar
iabl
e(butnotcl
assmemb ers)byusi
ngthevar
key
wor d.Thevari
ablest
il
lrecei
vesat ypeatcompil
etime,butthety
p ei
sprovi
d edbythecompi
ler
.For
moreinformat
ion,seeImpl
ici
tlyTypedLocalVar
iabl
es(C#Pr ogr
ammingGui
d e)
.

Insomecases
,i ti
sinconvenientt
ocreateanamedt y
pef ors
imples
etsofrelat
edv al
uesthaty
oud onot
i
ntendtostoreorpassout si
demethodbound
aries
.Youc ancr
eateanonymoustypesforthi
spurpos
e.For
moreinf
ormation,seeAnonymousTypes(C#ProgrammingGuide)
.

Ordi
naryval
uet yp esc
annothaveav al
ueofnull.However,youcanc reatenull
abl
evaluetyp
esb yaff
ixi
nga
?af t
erthetyp e.Forexample,i
nt?isaninttypethatcanal s
ohav et heval
uenull
.IntheCTS,null
able
ty
pesareinstanc esofthegeneri
cstructtyp
eSy stem.
Nullabl
e<T>.Nul l
abl
etypesareespec
ial
lyuseful
whenyouarep ass i
ngdatatoandfromd at
abasesinwhichnumer i
cv aluesmi
ghtbenull.

Cas
tingandTypeConv
ers
ions(
C#Pr
ogr
ammi
ngGui
de)
Vi
sualSt
udio2010
Ot
herVersi
ons

 5outof20r
atedt
hishel
pful-Rat
ethi
stop
ic

Up
dat
ed:June2010

Bec aus
eC#isstat i
cal
ly
-typ
edatc ompi
letime,afteravariabl
eisdecl
ared ,i
tc annotbed ec
lar
edagai
nor
usedt ost
orevaluesofanot
hertypeunles
st hattypeisconverti
bletothev ari
ab l
e'st
y p
e.Forexampl
e,
ther ei
snoconversi
onfromanintegertoanyar b
itrar
ys tri
ng.Therefore,aftery oudecl
areiasan
i
nt eger,y
oucannotas s
ignthes
tring"Hel
lo"toit,asi
ss howninthef ol
lowingc od
e.

C#

inti
;
i="Hel
lo"
;//Er
ror
:"Cannoti
mpl
ic
itl
yconv
ertt
ype'
str
ing'
to'
i
nt'
"

Howev
er,y
oumi
ghts
omet
imesneedt
ocop
yav
aluei
ntoav
ari
abl
eormet
hodp
aramet
erofanot
hert
ype.
Forexample,y
oumighthaveanintegerv
ariabl
ethatyouneedtop
asstoamet hodwhoseparameteris
typedasdoubl
e.Oryoumightneedtoassi
gnac l
assvari
abl
etoavari
ableofaninter
facetyp
e.Thes eki
nds
ofoperat
ionsarecal
ledt
ypeconversi
ons.InC#,youcanperf
ormthefoll
owi
ngkindsofconv
er s
ions:

 Impl i
citc onv er sions :Nos pec ials ynt axi sr equi r edb ecaus et hec onv er sioni st ypes af eandnod at
a
willbel os t.Examp lesi nclud ec onv er s i
onsf roms mal lert ol argeri nt egr alt ypes ,andc onv ersions
fromd er iv
edc las s
est ob asec lasses .
 Expl icitc onv er si
ons( cas ts) :Exp licitc onv ers ionsr equireac astop erat or .Cas tingisr equir ed
wheni nf ormat i
onmi ghtb elos ti nt hec onv ers ion,orwhent hec onv ers i
onmi ghtnots uc ceedf or
otherr eas ons .Ty picalexamp lesinc lud enumer icc onv ersi
ont oat ypet hathasl essprec i
sionora
smal l
err ange,andc onver sionofab ase-c lassi ns tanc et oad erivedc l
as s.
 Us er -def inedc onv ersions :Us er-d efinedc onv er s ionsar eper for medb ys pecialmet hod st haty ou
cand efinet oenab leexp lici
tandi mp licitc onv er sionsb etweenc us tomt yp est hatd onothav eab ase
class–d er i
v edc lassr el
at i
ons hip.Formor ei nfor mat i
on,s eeConv ers i
onOp erat ors(C#Pr ogrammi ng
Guide) .
 Conver s i
onswi thhel perc las ses:Toc onv ertb et weennon-c omp at iblet yp es,s uchasi nteger sand
Sy stem. Dat eTimeob jects ,orhexad ec imals tringsandb y
t ear ray s,y ouc anus et he
Sy stem. BitConv ert erc l
as s,t heSy st em. Conv er tc las s,andt hePar semet hodsoft heb ui lt-in
numer ict ypes ,s uchasI nt 32. Pars e.Formor ei nf or mat i
on,s eeHowt o:Conv er tab y teAr rayt oan
int(C#Pr ogr ammi ngGui de),Howt o:Conv er tas tr ingt oani nt( C#Pr ogr ammi ngGui d e),andHow
to:Conv er tBet weenHexad ec imalSt ringsandNumer i
cTy pes( C#Pr ogr ammi ngGui de).

I
mpl
ici
tConv
ers
ions

Forbuil
t-innumer i
ctypes,animpli
citconv er
sioncanbemad ewhent hevaluetob estoredcanfi
tintothe
vari
ablewithoutbeingtruncat
edorr ound edoff.Forexample,avariabl
eoft ypelong(8b y
teint
eger)c
an
stor
eanyv al
uethatani nt(4bytesona32-b i
tc omput
er)canstore.Int hefol
lowingexamp l
e,the
compil
erimp l
ic
itl
yconvertsthevalueont her i
ghtt oatypel
ongb eforeas s
igni
ngi ttobigNum.

C#

/
/Imp l
ici
tconver
sion.numl
ongcan
/
/holdanyvalueanintcanhol
d,andmor
e!
i
ntnum=2147483647;
l
ongbigNum=num;

Foracompl
etel
is
tofal
limp
lic
itnumer
icc
onv
ers
ions
,seeI
mpl
ic
itNumer
icConv
ers
ionsTab
le(
C#
Refer
ence)
.

Forref
erencet yp
es,animpli
citconver
sional
way
sexist
sfromaclas
stoanyoneofit
sd i
rectorind
irect
basecl
assesorinter
faces.Nos p
ecials
yntaxi
sneces
saryb
ecaus
ead er
ivedc
las
salwayscontai
nsallthe
membersofab asecl
ass.

Der
ivedd=newDer
ived
();
Bas
eb=d ;//Al
way
sOK.

Expl
ici
tConv
ers
ions

However,ifaconversi
oncannotb emadewi t
houtar iskoflosi
nginformation,thec ompi
lerrequi
resthat
youperformanexp l
ici
tconversi
on,whichiscaledac
l ast.Acastisawayofexp li
cit
lyinformingt
he
compi
lerthatyouintendtomaket heconversionandt hatyouareawar ethatd atalossmightocc
ur.To
perf
ormac as
t,sp
ec i
fythet y
pet haty
ouar ec as
tingt oinpar
enthesesinf rontoft hevalueorvar
iabl
eto
b
econv
ert
ed.Thef
oll
owi
ngp
rogr
amc
ast
sad
oub
let
oani
nt.Thep
rogr
amwi
llnotc
omp
ilewi
thoutt
hec
ast
.

C#

c
lassTes t
{
s
tat i
cv oidMain()
{
doublex=1234. 7;
i
nta;
//Cas td oub
letoint.
a=( i
nt )x;
System. Consol
e.Wri
teLi
ne(
a);
}
}
/
/Out p
ut :1234

Forali
stoftheexp
lic
itnumer
icc
onv
ers
ionst
hatar
eal
lowed
,seeExp
lic
itNumer
icConv
ers
ionsTab
le(
C#
Refer
ence)
.

Forr
efer
enc
ety
pes
,anexp
lic
itc
asti
srequi
redi
fyouneedt
oconv
ertf
romab
aset
ypet
oad
eri
vedt
ype:

C#

//Creat
eanewderi
vedtyp
e.
Gir
affeg=newGi
raffe(
);

//Imp
lic
itc
onv
ers
iont
obas
ety
pei
ssaf
e.
Ani
mala=g;

//Expl
ic
itconversi
oni srequir
edt ocastback
//toderi
vedtype.Not e:Thiswil
lcomp i
leb
utwill
//thr
owanexc eptionatr untimeift heri
ght-s
ide
//obj
ectisnotinfac taGi r
affe.
Gir
affeg2=( Gi
raffe)a;

Acastoperati
onbet
weenr ef
erencety
pesd oesnotchangetherun-t
imety
peoftheunderl
yingobj
ect
;it
onl
ychangesthetypeoft heval
uethatisbeingusedasar ef
erencetot
hatob
jec
t .Formoreinf
ormati
on,
seePol
ymorphis
m(C#Pr ogrammingGuide)
.

TypeConv
ers
ionExc
ept
ionsatRunTi
me

Insomereferenc
ety peconvers
ions,thecompi
lercannotdet
erminewhetherac as
twillb
ev al
id.I
tis
pos
sibl
eforac as
top erat
ionthatcomp i
lesc
orrectl
ytofai
latrunt i
me.Ass hownint
hef ol
lowi
ngexamp
le,
atypecastthatfai
lsatrunt i
mewi l
lcauseanI nv
ali
dCast
Except
iontobet hrown.

C#

c
lassAnimal
{
p
ubli
cv oidEat(
){Consol
e.Wri
teLi
ne(
"Eat
ing.
");}
p
ubli
cov erri
destr
ingToStri
ng()
{
r
etur
n"Iamanani
mal
."
;
}
}
c
las
sRept
il
e:Animal{}
c
las
sMammal:Ani
mal{}

c
lassUnSaf eCas
t
{
s
tat i
cvoidMain(
)
{
Test(
newMammal(
));

//Keepthecons
olewindowopenindebugmode.
Syst
em.Cons
ole.
Wr i
teLi
ne("
Pressanykeytoexi
t."
);
Syst
em.Cons
ole.
ReadKey()
;
}

s
tat i
cvoidTest(
Animala)
{
//CauseInval
idCastExc
epti
onatrunti
me
//becauseMammalisnotconver
tib
let
oRept
il
e.
Repti
ler=(Rep t
il
e)a;
}

C#prov
idest
hei
sandasop
erat
orst
oenab
ley
out
otes
tforc
omp
ati
bil
it
ybef
oreac
tual
lyp
erf
ormi
nga
cas
t

Boxi
ngandUnb
oxi
ng(
C#Pr
ogr
ammi
ngGui
de)
Vi
sualSt
udio2010
Ot
herVersi
ons

 38outof42r
atedt
hishel
pful-Rat
ethi
stop
ic

Up
dat
ed:Jul
y2010

Boxi
ngist hep r
ocessofc onv erti
ngav aluet ypetot het y
peobjec
tort oanyinterfacetypeimpl
ementedby
thi
svaluet y
pe.Whent heCLRb oxesav aluetype,itwr apstheval
uei ns
ideaSy s
tem.Objectandstor
esit
onthemanagedheap .Unb oxingextrac
t st hevaluety p
ef romtheobject.Boxi
ngisimpli
cit
;unboxi
ngis
expl
ic
it.Thec onceptofb oxingandunb oxingund erl
iest heC#unifi
edv i
ewoft hetypesystem,i
nwhicha
val
ueofanyt ypecanb et reatedasanob ject
.

I
nthef
oll
owi
ngexamp
le,t
hei
ntegerv
ari
abei
l sb
i oxedandas
signedt
oob
j to
ec .

C#
inti=123;
//Thefoll
owingl
ineb
oxesi
.
objec
to=i ;

Theob
j toc
ec ant
henb
eunb
oxedandas
signedt
oint
egerv
ari
abei
l :

C#

o=123;
i=(
int)
o;/
/unb
oxi
ng

Thef
oll
owi
ngexamp
lesi
ll
ust
rat
ehowb
oxi
ngi
sus
edi
nC#.

C#

//Stri
ng.Concatexamp l
e.
//Stri
ng.Concathasmanyv ersi
ons.Restthemous epoi
nteron
//Concatinthef oll
owings tatementtov eri
fythattheversi
on
//thatisusedher etakest hreeobjectarguments.Both42and
//truemustb eboxed .
Consol
e.Wri
teLine(String.Concat("
Answer "
,42,true)
);

//Li
stexample.
//Createali
stofobjec
tst
ohol
daheterogeneousc
oll
ect
ion
//ofelement
s.
Li
st<objec
t>mixed
Lis
t=newLis
t<ob
ject
>( )
;

//Addastri
ngelementtotheli
st.
mixed
Lis
t.Ad
d("
FirstGroup
:")
;

/
/Ad ds omeintegerst othelist.
f
or( intj=1;j<5;j ++)
{
//Res tthemous epointeroverjtover
ifyt
hatyouareadd
ing
//ani nttoalistofob j
ec ts
.Eachel
ementjisb
oxedwhen
//y ouaddjtomi xedLis
t .
mixedList
.Ad
d (
j);
}

//Addanot herstri
ngandmoreint
eger
s.
mixedLis
t.Add("
SecondGroup
:")
;
for(intj=5;j<10;j ++)
{
mixedLi
st.Add(j
);
}

/
/Di s
playt heelementsint heli
st.Declaretheloopvari
abl
eby
/
/us i
ngv ar ,s
ot hatthecomp il
eras s
ignsitstype.
f
oreach(v ariteminmi xedLis
t)
{
/
/Res tt hemous ep
oi nt
erov eritemt overi
fyt hatt
heelement
s
//ofmixed
Listareobjec
ts.
Consol
e.Wri
teLi
ne(i
tem);
}

/
/Thef oll
owi ngl oopsumst hes quar esoft hef i
rstgr oupofb oxed
/
/integer sinmi xedList.Thelistel ementsar eobj ect
s ,andcannot
/
/b emul tipl
iedorad dedt othes umunt i
ltheyar eunb oxed.The
/
/unb oxingmus tb ed oneexp l
icit l
y.
v
ars um=0;
f
or( varj=1;j<5;j ++)
{
/
/Thef oll
owi ngs tat ementc aus esacomp il
erer ror:Operator
/
/'* '
c annotb eap pliedtoop er andsoftyp e'object'and
/
/'obj ect'
.
/
/sum+=mi xed Lis
t[j]*mi xed List[
j])
;

/
/Aftertheli
stelementsareunboxed
,t hecomp
utat
iond
oes
/
/notcauseac ompi
lererror.
s
um+=( i
nt)mi
xedList[
j]*(int
)mi
xedLis
t[ j
];
}

//Thesumd i
spl
ayedis30,t
hes umof1+4+9+16.
Consol
e.Wr
iteLi
ne("
Sum:"+s um);

/
/Output:
/
/Answer42Tr ue
/
/Fir
stGr oup:
/
/1
/
/2
/
/3
/
/4
/
/SecondGr oup:
/
/5
/
/6
/
/7
/
/8
/
/9
/
/Sum:30

Per
for
manc
e

I
nr el
ationt osi
mp l
eassi
gnments,b
oxingandunb oxi
ngarecomputati
onall
yexpensiv
ep roces
ses.Whena
v
aluety peisboxed,anewobjec
tmus tbeall
ocatedandcons
t r
ucted.Toaless
erd egree,thecas
tr equi
red
f
orunb oxingisals
oexpensi
vecomputati
onal
ly.Formoreinformati
on,seePerfor
manc e.

Boxi
ng

Boxingisusedtostorevaluetypesi
nt hegarbage-coll
ectedheap.Boxi
ngisanimpli
citc
onver
sionofa
val
uet ypetothetypeob j
ec tortoanyinter
facet y
p eimplementedbythi
sval
uet y
pe.Boxi
ngav al
uetyp
e
all
ocatesanobjec
ti nst
anc eontheheapandc opi
est hevalueint
ot henewobjec
t.

Cons
idert
hef
oll
owi
ngd
ecl
arat
ionofav
alue-t
ypev
ari
abl
e:

C#
i
nti=123;

Thef
oll
owi
ngs
tat
ementi
mpl
ic
itl
yap
pli
est
heb
oxi
ngop
erat
ionont
hev
ari
abei
l :

C#

//Boxi
ngc
opiest
hev
alueofii
ntoob
jec
to.
obj
ecto=i;

Theresul
toft hi
sstatementisc
reatinganobjectref
er enceo,onthestack,thatref
erencesaval
ueof
thetypeint
,ont heheap.Thi
svalueisacopyofthevalue-typeval
ueas s
ignedtothevari
ablei
.The
dif
ferenc
eb et
weent hetwovari
ab l
es,iando,isi
ll
ustratedinthefol
lowingfi
gure.

Boxi
ngConv
ers
ion

I
tals
oposs
ibl
etop
erf
ormt
heb
oxi
ngexp
lic
itl
yasi
nthef
oll
owi
ngexamp
le,b
utexp
lic
itb
oxi
ngi
snev
er
r
equi
red
:

C#

inti=123;
objec
to=( ob
jec
t)i
;//exp
lic
itb
oxi
ng

Des
cri
pti
on

Thi
sexampleconvert
sani ntegervariab
leitoanobj
ectob yusi
ngboxing.Then,thevaluest
oredinthe
vari
abei
l ischangedfrom1 23to4 56.Theexampl
eshowsthattheori
ginalvaluet
y peandtheboxedobj
ect
usesep
aratememor yloc
at i
ons,andtherefor
ecanstored
iffer
entvalues.

Exampl
e

C#

c
las
sTes
tBoxi
ng
{
s
taticv
oidMain(
)
{
i
nti=123;

//Boxi
ngc
opiest
hev
alueofii
ntoob
jec
to.
obj
ecto=i;

//Changet
hev
alueofi
.
i=456;

//Thec
hangei nidoesnoteffectt
hev al
uestor edi
no.
Syst
em.Cons
ole.Wr
iteLi
ne("Theval
ue-typevalue={0}"
,i);
Syst
em.Cons
ole.Wr
iteLi
ne("Theobj
ect-typevalue={0}"
,o);
}
}
/
*Out put
:
Theval
ue-ty
pev alue=456
Theobj
ect-typ
ev alue=123
*
/

Thefol
l
owingexampledemonstr
atesacaseofinval
idunb
oxingandtheresul
ti
ngI
nval
idCas
tExc
ept
ion.
Usi
ngtryandcatch,anerrormessagei
sdis
playedwhentheerroroc
cur
s .

C#

c
lassTes tUnb
oxi
ng
{
s
tat icv
oidMain(
)
{
inti=123;
objec
to=i ;//imp
lic
itb
oxi
ng

t
ry
{
intj=(
shor
t)o;/
/at
temp
ttounb
ox

Syst
em.Cons
ole.
WriteLi
ne(
"Unboxi
ngOK."
);
}
c
atc
h( Sy
stem.
Inval
idCast
Excepti
one)
{
Syst
em.Cons
ole.
WriteLi
ne(
"{0}Error
:Inc
orrec
tunb
oxi
ng.
",e.
Mes
sage)
;
}
}
}

Thi
spr
ogr
amout
put
s:

Sp
eci
fiedc
asti
snotv
ali
d.Er
ror
:Inc
orr
ectunb
oxi
ng.

I
fyouc
hanget
hes
tat
ement
:
i
ntj=(
shor
t)o;

t
o:

i
ntj=(
int
)o;

t
hec
onv
ers
ionwi
llb
eper
for
med
,andy
ouwi
llgett
heout
put
:

Unb
oxi
ngOK.

Unb
oxi
ng

Unboxi
ngisanexpli
citconvers
ionfromthetyp
eobjec
ttoaval
uet y
peorf
romani
nter
fac
ety
pet
oav
alue
typ
et hati
mplementstheinterfac
e.Anunboxi
ngop
erati
onc
onsis
tsof:

 Chec
kingtheob
jec
ti ns
tancetomakesurethatiti
sab oxedval
ueoft
hegi
venv
aluet
ype.
 Copy
ingtheval
uefromt hei
nst
anceint
ot heval
ue-ty
pev ari
abl
e.

Thef
oll
owi
ngs
tat
ement
sdemons
trat
ebot
hboxi
ngandunb
oxi
ngop
erat
ions
:

C#

inti=123; //av al
uetype
objec
to=i ; /
/b oxi
ng
intj=(int
)o;//unboxi
ng

Thef
oll
owi
ngf
igur
edemons
trat
est
her
esul
toft
hep
rev
iouss
tat
ement
s.

Unb
oxi
ngConv
ers
ion

Fort heunboxi
ngofv aluetypestosucceedatr
unt i
me,thei
tembeingunb
oxedmustbear ef
erenc
et oan
objectthatwasp revi
ouslycreatedbyboxi
nganinst
anceofthatv
aluetyp
e.Att
emp t
ingtounboxnull
causesaNul l
ReferenceExcep
t i
on.Attempti
ngtounboxaref
erenc
et oaninc
ompat
ibl
ev al
uetypecauses
anI nval
idCast
Excepti
on.

Us
ingTyped
ynami
c(C#Pr
ogr
ammi
ngGui
de)
Vi
sualSt
udio2010
Ot
herVersi
ons

 38outof62r
atedt
hishel
pful-Rat
ethi
stop
ic

VisualC#2010i nt roduc esanewt yp


e,d ynami c.Thet ypeisas tatict y
p e,butanob j
ec toftyp
ed ynamic
bypassess tati
ct ypechec king.I
nmos tcas es,itfunct i
onslikeithast y peobject.Atc ompi
let
ime,an
elementt hatist y
p edasd ynami
ci sassumedt osuppor tanyop eration.Ther efor
e,youd onothavet obe
concernedab outwhet hert heobjectget sitsvaluefr omaCOMAPI ,f romad y
namiclanguagesuchas
IronPython,f r
omt heHTMLDoc umentOb jectMod el(DOM) ,fromr eflection,orfroms omewhereelseinthe
program.Howev er,ift hec odei
snotv alid,errorsarec aughtatr unt ime.

Forexamp l
e,ifinstancemet hode xamp l
eMethod 1inthef ol
lowingc odehasonlyonep ar
ameter,the
compil
errecognizesthatt hef i
rstc al
ltothemet hod,ec.examp leMet hod1(
10,4),i
snotv al
idbec
auseit
contai
nst woargument s.Thec allcausesacomp il
ererror.Thes econdc allt
othemet hod,
dynamic_ec.examp l
eMet hod1(10,4) ,i
snotc heckedbyt hec ompil
erb ecausethety
p eofdynamic
_ecis
dynamic.Therefore,nocomp il
erer rorisrep
or ted.Howev er
,t heerr ordoesnotescapenoti
ceindef
ini
tel
y.
Itiscaughtatr unt i
meandc ausesar un-ti
meexc ep
tion.

C#

s
tat icvoidMai n(s
tr i
ng[]args)
{
Examp leCl
as sec=newExamp leCl
ass()
;
//Thef ol
lowingc al
ltoexamp l
eMethod1c
ausesacomp
ilererr
or
//ifexamp l
eMet hod1hasonlyonep ar
ameter
.Unc
ommentt heli
ne
//t oseet heer ror.
//ec.examp l
eMet hod1(10,4)
;

d
ynami
cd y
nami c
_ec=newExamp leClas
s();
/
/Thefoll
owinglineisnotidentifiedasaner r
orbyt
he
/
/compi
ler,butitcausesar un-timeexc ept
ion.
d
ynami
c_ec.examp l
eMethod
1( 10,4) ;

/
/Thefol
lowingc al
lsalsodonotcausecompil
ererror
s,whet
her
/
/appr
opriatemet hodsexi
stornot .
d
ynami
c_ec.someMet hod
("s
omear gument",7,nul
l)
;
d
ynami
c_ec.nonexistent
Met hod
();
}

C#

c
lassExampl
eCl
ass
{
p
ubli
cExampl
eCl
ass
(){}
p
ubli
cExampl
eCl
ass
(intv
){}
p
ubl
icv
oidexamp
leMet
hod
1(i
nti
){}

p
ubl
icv
oidexamp
leMet
hod
2(s
tri
ngs
tr){}
}

Therol
eoft hecompi
lerintheseexamplesi
st opackagetoget
heri nf
or mationaboutwhateachst
atement
i
sp r
oposi
ngt odototheobjectorexpressi
ont hatistyp
edasd ynamic.Atr unti
me,thestoredi
nformat
ion
i
sexamined,andanys t
atementthatisnotv al
idcausesarun-timeexc ept
ion.

Theresul
tofmostd
ynamicop
er ati
onsisi
tsel
fdynamic.Forexampl
e,i
fyourestt
hemousepoi
nterov
er
theuseoftes
tSuminthefol
lowingexampl
e,Intel
li
Sensedis
playst
hetype(
loc
alvar
iab
le)d
ynamic
test
Sum.

C#

dynamicd=1;
vartestSum=d+3;
//Restt hemousepoint
erovertest
Sumi
nthef
oll
owi
ngs
tat
ement
.
System.Consol
e.Wr
iteLi
ne(
testSum);

Operationsinwhichtheresul
tisnotd ynamicinc
ludeconver
sionsf
romdynami
ctoanot
hertyp
e,and
constr
uc torcall
sthatinc
ludeargument softypedynamic
.Forexampl
e,thety
peoftestI
nst
anceinthe
fol
lowingd ecl
arati
onisExampleClas
s,notd ynamic.

C#

v
art
est
Ins
tanc
e=newExamp
leCl
ass
(d)
;

Conv
ers
ionexamp
lesar
eshowni
nthef
oll
owi
ngs
ect
ion,"
Conv
ers
ions
."

Conv
ers
ions

Convers
ionsbet
weendynami
cobj
ectsandot
hert
ypesar
eeas
y.Thi
senab
lest
hed
evel
opert
oswi
tch
betweendynami
candnon-dy
nami
cbehavi
or.

Anyob
jec
tcanb
econv
ert
edt
ody
nami
cty
pei
mpl
ic
itl
y,ass
howni
nthef
oll
owi
ngexamp
les
.

C#

d
ynami
cd1=7;
d
ynami
cd2="astr
ing"
;
d
ynami
cd3=Sys
tem.DateTi
me.Today;
d
ynami
cd4=Sys
tem.Di
agnosti
cs.Proc
ess
.Get
Proc
ess
es(
);

Conv
ers
ely
,ani
mpl
ic
itc
onv
ers
ionc
anb
edy
nami
cal
lyap
pli
edt
oanyexp
res
sionoft
yped
ynami
c.
C#

i
nti=d 1;
str
ings tr=d 2;
DateTimed t=d3;
System.Diagnosti
cs.
Proc
ess
[]p
roc
s=d
4;

Ov
erl
oadRes
olut
ionwi
thAr
gument
sofTyped
ynami
c

Over l
oadresol
uti
onoccursatrunt i
mei nsteadofatc ompil
etimeifoneormoreoft heargumentsina
methodc al
lhavethetypedynamic,orift hereceiv
eroft hemethodcalli
softypedynamic.Inthefol
lowing
examp l
e,iftheonl
yaccessi
bleexamp l
eMet hod2met hodi
sd efi
nedtotakeas t
r i
ngargument,sendngd
i 1
ast heargumentdoesnotcauseac ompilererror,butitdoescausearun-ti
meexc ept
ion.Over
load
resoluti
onfail
satruntimeb ec
auset her un-ti
met ypeofd 1i
sint,andexampleMethod2requi
resas tr
ing.

C#

//Val
id.
ec.
exampleMet
hod
2("
ast
ring"
);

//Thef oll
owings tatementdoesnotcauseac ompil
ererror
,event
hougheci
snot
//d ynamic.Arun-t i
meexc ep
tioni
sraisedbecausetherun-ti
metypeofd
1isi
nt.
ec.exampleMethod2(d1);
//Thef oll
owings tatementdoescaus
eac omp
ilererror
.
//ec.examp l
eMethod2(7);

Dynami
cLanguageRunt
ime

Thed y
nami cl
anguageruntime(DLR)isanewAPIin.NETFramework4.Itp
r ov
idest
hei
nfrastr
uct
urethat
supportsthedynamictyp
ei nC#,andalsotheimpl
ementat
ionofdy
namicprogrammi
ngl
anguagess
uchas
IronPythonandIronRuby.Formoreinformat
ionaboutt
heDLR,seeDynami
cLanguageRunti
meOverv
iew.

COMI
nter
op

Vis
ualC#2010incl
udesseveralfeatur
esthatimpr
ov etheexper
ienceofint
eroper
atingwi
thCOMAPIs
suchastheOf
ficeAutomationAPIs.Amongtheimprovementsaretheuseofthedynamict
ype,andof
namedandopti
onalarguments.

ManyCOMmet hodsallowf orvariat i


oninargumentt ypesandr et urntypeb yd es
ignatingthet y
pesas
object.Thishasnec es s
itatedexp l
ic i
tcast
ingoft hevaluest oc oor
d i
natewi thst r
onglytypedvari
abl
esin
C#.I fyouc ompil
ebyus i
ngt he/ l
ink( C#Compil
erOp ti
ons )option,theintrod uct
ionoft hedynamictype
enablesy outotreatt heoc currenc esofobjec
tinCOMs ignatur esasiftheywer eoft ypedynamic
,and
therebyt oavoidmuc hoft hec asting.Forexample,thef ol
lowings tatementsc ontrasthowy ouacces
sac el
l
inaMi crosoftOffi
ceExc elspr
ead sheetwiththed ynamict ypeandwi thoutt hed ynamictype.

C#

/
/Bef
oret
hei
ntr
oduc
tionofd
ynami
c.
((
Excel.
Range)excel
App.
Cell
s[1,1])
.Val
ue2=" Name"
;
Excel
.Rangerange2008=(Excel.
Range)exc
elApp.
Cel
ls[
1,1]
;

C#

//Aftertheintrod
uc ti
onofd y
namic
,theac ces
stotheValuepr
oper
t yand
//theconversi
ont oExcel
.Rangearehandledbytherun-t
imeCOMbinder.
excel
App.Cel
ls[
1,1].Val
ue=" Name"
;
Excel
.Rangerange2010=exc el
App.
Cell
s[1,1];

Howt
o:Conv
ertas
tri
ngt
oani
nt(
C#Pr
ogr
ammi
ngGui
de)
Vi
sualSt
udio2010
Ot
herVersi
ons

 31outof58r
atedt
hishel
pful-Rat
ethi
stop
ic

Theseexamplesshows omediff
erentwaysyouc anconv
er tastri
ngt oanint.Suchaconvers
ioncanbe
usefulwhenobtainingnumeri
cali
nputfromac ommandlineargument,forexamp l
e.Si
mil
armethodsexi
st
forconvert
ingstringstoothernumeri
ct y
pes,suchasfloatorlong.Thetablebel
owli
stssomeofthose
methods.

Numer
icTy
pe Met
hod

d
eci
mal ToDec
imal
(St
ring)

f
loat ToSi
ngl
e(St
ring)

d
oub
le ToDoub
le(
Str
ing)

s
hor
t ToI
nt16(
Str
ing)

i
nt ToI
nt32(
Str
ing)

l
ong ToI
nt64(
Str
ing)

us
hor
t ToUI
nt16(
Str
ing)

ui
nt ToUI
nt32(
Str
ing)

ul
ong ToUI
nt64(
Str
ing)

Examp
le
Thi
sexamp lecal
lstheToI
nt32(St
ring)met hodtoconver
tani np
uts tr
ingtoanint.Theprogramcatches
thet womostcommonexcepti
onsthatc anb ethr
ownb ythismethod.I
ft henumbercanb
eincremented
withoutoverf
lowingthei
ntegerstoragelocati
on,theprogramad d
s1t otheres
ultandpri
ntstheoutput.

C#

i
ntnumVal=-1;
b
oolrep
eat=true;

whil
e(repeat==true)
{
Cons
ole.Wri
teLi
ne("
Ent
eranumb
erb
etween−2,
147,
483,
648and+2,
147,
483,
647(
inc
lus
ive)
.")
;

s
tri
ngi
nput=Cons
ole.
Read
Line(
);

//ToI nt32cant hr owFor mat Exc eptionorOv erfl


owExcep
t i
on.
try
{
numVal=Conv er t.ToI nt 32(input);
}
catch( Format Exc ep ti
one)
{
Cons ol
e.Wr i
t eLi ne( "Inp uts tringisnotas equenceofdigit
s."
);
}
catch( Overf
lowExc eptione)
{
Cons ol
e.Wr i
t eLi ne( "Thenumb erc annotf i
ti nanInt32.
");
}
finally
{
if( numVal<I nt 32. MaxVal ue)
{
Cons ol
e.Wr i
t eLi ne("Thenewv alueis{0}",numVal+1) ;
}
else
{
Cons ol
e.Wr i
t eLi ne("numVal cannotb einc r
ementedbeyonditsc
urr
entv
alue"
);
}
}
Cons ole.WriteLi ne( "Goagai n?Y/ N");
stringgo=Cons ol e.Read Line();
if(go==" Y"||go==" y")
{
rep eat=t r ue;
}
else
{
rep eat=f al se;
}
}
//Keepthec onsol
eopenindebugmode.
Consol
e.Writ
eLine("Pr
essanykeytoexi
t."
);
Consol
e.ReadKey()
;

Anotherwayofconv
er t
ingastri
ngtoaninti
sthroughthePar
seorTryParsemethod
softhe
Syst
em. I
nt32st
ruct.TheToUI
nt32methodus
esParseinter
nal
ly.I
fthestr
ingisnotinav
ali
dfor
mat
,
Parset
hrowsanexc
eptionwher
easTryPar
sedoesnotthrowanexcep
tionbutret
urnsf
als
e.Theexamp
les
bel
owdemonst
ratebot
hs uc
cess
fulanduns
ucc
essfulc
all
st oPar
seandTryPars
e.

C#

i
ntnumVal =I nt32.
Parse(
"-105"
);
Consol
e.WriteLi
ne(numVal
);
//Output:-105

C#

//Try Par seret urnst rueift heconv ersi


ons ucc
eeded
//ands torest her esultint hespecifiedvari
ab l
e.
intj;
boolres ult=I nt 32.
Tr yParse("-105",outj )
;
if(true==r esult )
Cons ole.WriteLine(j);
else
Cons ole.WriteLine("Stringc ouldnotb eparsed."
);
//Out put :-105

C#

t
ry
{
i
ntm=I nt32.Parse("
abc
");
}
c
at ch(
For matExcep t
ione)
{
Cons
ole.WriteLine(e.
Mess
age)
;
}
/
/Out put:Inputs tri
ngwasnotinac
orr
ectf
ormat
.

C#

s
tri
nginputStri
ng=" abc"
;
i
ntnumValue;
b
oolpar
sed=I nt32.
Tr y
Parse(
inp
utSt
ring,outnumVal
ue)
;

i
f( !
parsed
)
Cons
ole.
Wri
teLi
ne(
"Int
32.
Try
Par
sec
oul
dnotp
ars
e'{
0}'
toani
nt.
\n"
,inp
utSt
ring)
;

/
/Out
put
:Int
32.
Try
Par
sec
oul
dnotp
ars
e'ab
c't
oani
nt.

You might also like