.NETGotachas
ByVenkatSubramaniam
...............................................
Publisher:O'Reilly
PubDate:May2005
ISBN:0-596-00909-7
Pages:400
TableofContents|Index
Likemostcomplextasks,.NETprogrammingisfraughtwithpotentialcostly,andtimeconsuminghazards.ThemillionsofMicrosoftdevelopersworldwidewhocreate
applicationsforthe.NETplatformcanattesttothat.Thankfullythere'snowabookthat
showsyouhowtoavoidsuchcostlyandtime-consumingmistakes.It'scalled.NET
Gotchas.
Theultimateguideforefficient,pain-freecoding,.NETGotchasfromO'Reillycontains75
common.NETprogrammingpitfalls--andadviceonhowtoworkaroundthem.Itwillhelp
yousteerawayfromthosemistakesthatcauseapplicationperformanceproblems,orso
taintcodethatitjustdoesn'tworkright.
Thebookisorganizedintoninechapters,eachfocusingonthosefeaturesandconstructs
ofthe.NETplatformthatconsistentlybaffledevelopers.Withineachchapterareseveral
"gotchas,"withdetailedexamples,discussions,andguidelinesforavoidingthem.Nodoubt
aboutit,whenapplied,theseconcisepresentationsofbestpracticeswillhelpyouleada
moreproductive,stress-freeexistence.
What'smore,becausecodeexamplesarewritteninbothVB.NETandC#,.NETGotchasis
ofinteresttomorethan75percentofthegrowingnumbersof.NETprogrammers.Soif
you'rea.NETdeveloperwho'smiredinthetrenchesandyearningforabetterway,this
bookismostdefinitelyforyou.
.NETGotachas
ByVenkatSubramaniam
...............................................
Publisher:O'Reilly
PubDate:May2005
ISBN:0-596-00909-7
Pages:400
TableofContents|Index
Copyright
Dedication
Preface
WhoThisBookIsFor
WhatYouNeedtoUseThisBook
MeasureofPerformance
ConventionsUsedinThisBook
UsingCodeExamples
CommentsandQuestions
Safari®Enabled
Acknowledgments
Chapter1.CLR/FrameworkGotchas
GOTCHA#1Typealiassizedoesn'tmatchwhatyou'refamiliarwith
GOTCHA#2structandclassdifferinbehavior
GOTCHA#3Returningvaluetypesfromamethod/propertyisrisky
GOTCHA#4Youcan'tforcecallstoyourvalue-typeconstructors
GOTCHA#5Stringconcatenationisexpensive
GOTCHA#6Exceptionsmaygounhandled
GOTCHA#7Uninitializedeventhandlersaren'ttreatedgracefully
GOTCHA#8Divisionoperationisn'tconsistentbetweentypes
GOTCHA#9TypelessArrayListisn'ttype-safe
GOTCHA#10Type.GetType()maynotlocatealltypes
GOTCHA#11Publickeyreportedbysn.exeisinconsistent
Chapter2.VisualStudioandCompilerGotchas
GOTCHA#12Compilerwarningsmaynotbebenign
GOTCHA#13Orderingofcatchprocessingisn'tconsistacrosslanguages
GOTCHA#14Type.GetType()mightfailatrun-time
GOTCHA#15rethrowisn'tconsistent
GOTCHA#16DefaultofOptionStrict(off)isn'tgood
GOTCHA#17VersioningmayleadtoSerializationheadaches
GOTCHA#18CreatingWebappscanbepainful
GOTCHA#19NamingXMLdocumentationforIntelliSensesupportisn'tintuitive
Chapter3.LanguageandAPIGotchas
GOTCHA#20Singletonisn'tguaranteedprocess-wide
GOTCHA#21DefaultperformanceofData.ReadXMLData.ReadXML
GOTCHA#22enumlackstype-safety
GOTCHA#23CopyConstructorhampersexensibility
GOTCHA#24Clone()haslimitations
GOTCHA#25Accesstostatic/Sharedmembersisn'tenforcedconsistently
GOTCHA#26Detailsofexceptionmaybehidden
GOTCHA#27Objectinitializationsequenceisn'tconsistent
GOTCHA#28Polymorphismkicksinprematurely
GOTCHA#29Unittestingprivatemethodstestingprivatemethods
Chapter4.LanguageInteroperabilityGotchas
GOTCHA#30CommonLanguageSpecificationComplianceisn'tthedefault
GOTCHA#31Optionalparametersbreakinteroperability
GOTCHA#32Mixingcasebetweenclassmembersbreaksinteroperability
GOTCHA#33Namecollisionwithkeywordsbreaksinteroperability
GOTCHA#34Defininganarrayisn'tconsistent
Chapter5.GarbageCollectionGotchas
GOTCHA#35WritingFinalize()israrelyagoodidea
GOTCHA#36ReleasingmanagedresourcesinFinalize()canwreakhavoc
GOTCHA#37Rulestoinvokebase.Finalize()aren'tconsistent
GOTCHA#38DependingonFinalize()cantieupcriticalresources
GOTCHA#39UsingFinalize()ondisposedobjectsiscostly
GOTCHA#40ImplementingIDisposableisn'tenough
GOTCHA#41UsingtheDisposeDesignPatterndoesn'tguaranteecleanup
Chapter6.InheritanceandPolymorphismGotchas
GOTCHA#42RuntimeTypeIdentificationcanhurtextensibility
GOTCHA#43Usingnew/shadowscauses"hideoushiding"
GOTCHA#44Compilersarelenienttowardforgottenoverride/overrides
GOTCHA#45Compilersleantowardhidingvirtualmethods
GOTCHA#46Exceptionhandlingcanbreakpolymorphism
GOTCHA#47Signaturemismatchescanleadtomethodhiding
Chapter7.MultithreadingGotchas
GOTCHA#48TheThreadclassThreadclass
GOTCHA#49Foregroundthreadsmaypreventaprogramfromterminating
GOTCHA#50Backgroundthreadsdon'tterminategracefully
GOTCHA#51Interrupt()kicksinonlywhenathreadisblocked
GOTCHA#52ThreadAbortExceptionahotpotato
GOTCHA#53Environment.Exit()bringsdowntheCLR
GOTCHA#54ResetAbort()mayleadtosurprises
GOTCHA#55Abort()takestimetocleanup
GOTCHA#56CallingType.GetType()maynotreturnwhatyouexpect
GOTCHA#57Lockingongloballyvisibleobjectsistoosweeping
GOTCHA#58Threadsfromthethreadpoolarescarce
GOTCHA#59Threadsinvokedusingdelegatesbehavelikebackgroundthreads
GOTCHA#60Passingparameterstothreadsistricky
GOTCHA#61Exceptionsthrownfromthreadsinthepoolarelost
GOTCHA#62AccessingWinFormcontrolsfromarbitrarythreadsisdangerous
GOTCHA#63Web-serviceproxymayfailwhenusedformultipleasynchronous
calls
GOTCHA#64Raisingeventslacksthread-safety
Chapter8.COM-InteropandEnterpriseServicesGotchas
GOTCHA#65ReleaseofCOMobjectisconfusing
GOTCHA#66UsinginterfacepointersaftercallingReleaseComObject()willfail
GOTCHA#67Cross-apartmentcallsareexpensive
GOTCHA#68Defaultapartmentofmainthreadisinconsistentacrosslanguages
GOTCHA#69STAThreadattributemayhavenoeffectonyourmethods
GOTCHA#70SpatteringaccesstoCOMcomponentsmakescodehardto
maintain
GOTCHA#71Auto-generatingGUIDforyourclassesleadstoversioningwoes
GOTCHA#72AllbutoneoftheClassInterfaceoptionsareineffective
GOTCHA#73SimplyturningtheswitchforCOMinteropisdangerous
GOTCHA#74ServicedComponentsimplementedinconsistentlyonXPand2003
GOTCHA#75AutoCompletecomeswithundesirablesideeffects
Appendix:Resources
Bibliography
OntheWeb
Colophon
AbouttheAuthor
Colophon
Index
.NETGotchas
byVenkatSubramaniam
Copyright©2005O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or
Editor:
JohnOsborn
DevelopmentEditor:
RalphDavis
ProductionEditor:
PhilipDangler
CoverDesigner:
EllieVolckhausen
InteriorDesigner:
MarciaFriedman
PrintingHistory:
May2005:
FirstEdition.
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
.NETGotchas,theimageofahammerheadshark,andrelated
tradedressaretrademarksofO'ReillyMedia,Inc.
Microsoft,MSDN,the.NETlogo,VisualBasic,VisualC++,
VisualStudio,andWindowsareregisteredtrademarksof
MicrosoftCorporation.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-596-00909-7
[M]
Dedication
Tomyteachers:Mr.J.Govindaswamy,Dr.Dayalan,
Mrs.KrantiRamakrishnan,andProfessorN.
Venkateswaran,whospentcountlesshoursto
motivate,inspire,andturnmearound.Idedicate
achievementsinmyprofessionallifetoyou.
VenkatSubramaniam
Preface
Ifyou'vepickedupthisbook,you'reprobablyamongthemany
programmerswhohavecometoappreciatehowpowerfulthe
Microsoft.NETFrameworkcanbeasaplatformfor
development.Butyou'vealsolearnedthat,aswithany
platform,.NEThasquirksthatcantripupeventhesavviest
programmer.Haveyoubeensurprisedbyfeaturebehaviorin
the.NETlanguageorthe.NETFrameworkincludingtheCLRand
FrameworkClassLibraryorinVisualStudio.NET?Ifyou've
workedwith.NETforanylengthoftime,Isuspectyouare
noddingyourheadwithasighofagreement.Experience
teachesuswhattodoandwhattoavoid,butinprogramming,
wecommonlyacquireourknowledgethehardway:bymaking
costly,hard-to-debugandtime-consumingmistakes.Mygoalin
writingthisbookistosavemyfellowdevelopersfromsomeof
thatpain,bysharingtheexperiences(andbadcode)that
broughtthepitfallsof.NETtolightforme,andshowingyou
howtoavoidthem(andwritecodethatworks).
Istartedworkingwith.NETwhenitwasinpre-releaseBeta2.
Thefollowingyearshavebeenalotoffun.However,therehave
beendays(andnights)whenthingswerenotsoobvious,when
thecodewouldbehave,shallIsay,strangely,givenmy
expectationsasanexperienceddeveloper.
Thegotchasandguidelinespresentedinthisbookhavecome
fromthreesources:First,theinsightsIhavegainedfrom
developing.NETapplications.Second,thequestionsraisedby
thehundredsofinquisitivesoftwaredevelopersI'vehadthe
privilegeoftraining.Third,thethought-provokingarticlesand
discussionsIhavecomeacrossatsymposiums,user-group
meetings,theInternet,aswellastheMSDNdocumentation
itself.
What'saGOTCHA?AccordingtoMerriam-Webster,gotchais
definedasfollows:
"MainEntry:got:cha
Pronunciation:'gä-ch&
Function:noun
Etymology:alterationofgotyou
:anunexpectedusuallydisconcertingchallenge,revelation
Forme,.NETgotchasarethosethingsthatpopup
unexpectedlywhenyou'reprogrammingin.NET.Thingsthatare
buried,justwaitingforyou!Itisasiftheenvironmentisthere,
awareofitsownidiosyncrasies,watchingyouasyouwork,but
unable(orunwilling)towarnyouasyoufallintooneofits
traps.
I'mnottalkingaboutthoselittleannoyingquirksinVisual
Studiothatmakeitmisbehaveoccasionally,northetransient
flawsyouseewhileworkingwiththedebuggeroreditor.Inthis
book,Ifocusonthe.NETFrameworkandlanguagefeatures
thathaveconsistentlyexhibitedbehaviorthatwasnotobvious
tome.Whyshouldyoubeinterestedinlearningaboutthese?
Becauseknowingtheselittlegotchaswillhelpyouavoid
mistakes.You'lldevelopapplicationsmorequickly.Some
solutionswillimprovetheperformanceofyourapplications.
Otherswillhelpyoustayclearofproblemsthatwillmakeyour
codeincorrect.Yetotherswillhelpyouwithhiddenproblems
suchaspropergarbagecollection.
Mostbookson.NETstartbyassumingthatthereaderknows
littleaboutit.Thosebooksareintendedtobringreadersupto
speedwith.NEToroneofitsassociatedlanguages.Asmore
andmorepeoplelearntouseanytechnology,aneedarisesnot
justtolearnhowuseit,buthowtouseitwell,anddothings
right.Becauseexperienceisourbestteacher,italwaystakesa
fewyearsforbooksthataddressthoseneedstoappear.
Considermyowncase,someyearsago.Ihadtakenthetimeto
learntheC#languageandwasaseriousdeveloper(orsoI
thought),workinghardtoputthefeaturesandfacilitiesofthe
languagetoprudentuse.Onedayintheearly'90s,Iwalked
intomycolleague'sofficeandfoundabookentitledC++FAQs
byMarshalClineonhertable.Pickingitup,Iasked"Whywould
anyonewhoknowsC++readabookthatlistsquestionsand
answers?"Shesmiled.Iflippedthroughafewpages,and
beforeIknewit,IfoundIhadbeenstandingthereforseveral
minutesreadingthebook,pageafterpage.Shefinally
interruptedandsaid,"WhywouldanyonewhoknowsC++be
readingthatbookforsolong?"Ifoundittobeinvaluableand
boughtacopyformyself(andIstillhavethatbookanditsnext
editioninmylibrary!)OthergreatbooksthatIhaveenjoyed
readingareEffectiveC++andMoreEffectiveC++byScott
Meyers,EssentialCOMbyDonBoxetal.,andEffectiveJavaby
JoshuaBloch.
Programmingin.NEThasenteredastagewherealarge
numberofdevelopershavelearnthowtoprogramwhatwasa
brandnewplatformonlyafewyearsago.Thetimehasarrived
forbooksthatteachgoodpractices.Ihopethisbookwillserve,
liketheclassicsonCOMandC++thathaveprecededit,to
educatesoftwaredevelopersonthedosanddon'tsof
programmingthe.NETplatform.
WhoThisBookIsFor
Thisbookisintendedforthe.NETprogrammerinthetrenches.
ThisincludesbothC#andVB.NETprogrammers.Iassumethat
youarefairlyfamiliarwith.NETprogrammingusingeitherC#
orVB.NET.Ialsoassumethatyouareacquaintedwiththe
termsandvocabularyusedbyMicrosoftindescribingthe.NET
platform.Inadditiontoprogrammers,projectleadsandsenior
programmersmayfindthisbookhelpfulinsettingstandards
andguidelinesfortheirdevelopmentteams.
HowThisBookIsOrganized
.NETGotchasisorganizedintoeightchapters,eachfocusingon
adifferentareaofinterestin.NET.Eachitemhasaname,title,
andincludescodeexamples,discussions,andguidelines"Ina
Nutshell."TheitemsaregroupedintotheareathatIfindtobe
themostappropriate.Attheendofeachitem,relatedgotchas
arereferencedforyourconvenience.Theexamplesare
presentedinbothC#andVB.NET(clearlymarkedsoyoucan
easilyidentifythesewithouthavingtoexaminethecode).The
codeislabeledwiththedirectorywhereyoucanfindthe
examplewhenyoudownloadthesourcecodefromtheonline
resource.TheoutputshownisfromtheC#code,unlessthe
outputfromC#differsfromtheVB.NEToutput,asisthecase
inafewgotchas.Wheretheyaredifferent,boththeC#output
andtheVB.NEToutputareshownanddiscussed.
CLR/FRAMEWORKGOTCHAS
TheCommonLanguageRuntime(CLR)andthe.NETframework
provideprogrammerswithahighlevelofabstractionandease
ofuse.Theypavethewayforwritingcode,moreorless
consistently,inanyofthedifferentlanguagessupportedby
.NET.However,thereareaspectsofboththatareconfusing,
misleading,orpronetomisuse.Also,certainfeaturesand
choicescanimpactthebehaviororperformanceofyourcode.
InthischapterIfocusonthoseissues.
VISUALSTUDIOANDCOMPILERGOTCHAS
ThetranslationofyoursourcecodeintoMicrosoftIntermediate
Language(MSIL)isthejoboftheC#andVB.NETcompilers.
However,therearethingsthatare"lostinthetranslation."
While.NETallowsyoutodevelopcodeinthelanguageofyour
choice,therearethingsthatcertaincompilersdonotlookout
for.InthischapterIdiscussissuesthatwillsurpriseyouinthe
areaofprogramcompilationandtheuseofVisualStudiofor
development.Also,youwilllearnabouttheinconsistencies
betweenthedifferentlanguagecompilers.
LANGUAGEANDAPIGOTCHAS
.NETlanguagessupportobject-orienteddevelopment,while
avoidingsomeoftheperilsofpowerful(buttreacherous)
languageslikeC++.Unfortunately,the.NETlanguageshave
introducedfeaturesthatleadtopoorobject-orientedpractices.
Furthermore,whileyourexperiencewithotherlanguagesmay
leadyoutoexpectthatcertainfeatureswillbehaveinfamiliar
ways,with.NETyouwilllearnthatthisisnotalwaysso.
LANGUAGEINTEROPERABILITYGOTCHAS
TheMSIListhecorelanguageof.NET.Codewrittenindifferent
.NETsupportedlanguagesistranslatedintoMSIL.Thisprovides
youtheabilitytointeroperatewithcodewrittenindifferent
languagesinapowerfulandusefulway.Youcanusethe.NET
languageofyourchoicetheonethatyouaremostcomfortable
with.Yourteamcanmixdifferentlanguagesindevelopingyour
system.Whileallthissoundsterrific,arethereanyissuesthat
willgetintheway?Inthischapteryouwilllearntheissuesthat
canaffectyoureffortstointeroperatebetween.NETlanguages.
GARBAGECOLLECTIONGOTCHAS
.NETprovidesautomaticgarbagecollection.Thereisnothingwe
havetodoorworryaboutintermsofobjectlifetime.Justsit
backandrelax,we'retold.Doesthatsoundtoogoodtobe
true?Whilegarbagecollectionisautomatic,itmaynotdoits
workonthescheduleyoumightprefer.Aslongasyouare
dealingwithonlymanagedresourcesthisisnotaproblem.
However,therealityisthatyoumustoftencontendwith
unmanagedresources,whichtheCLRwon'tknowhoworwhen
tocleanup.Inthischapteryouwilllearnaboutthevarious
issuesrelatedtogarbagecollectionandhowtowritecodethat
workscorrectly.
INHERITANCEANDPOLYMORPHISMGOTCHAS
Inheritanceandpolymorphismarecorefeaturesinobjectorientedprogramming.Comparedtootherobject-oriented
languages,.NEThasintroducedkeywordsandfacilitiesthatare
eithernewordifferent.Whilethesewereprovidedwithgood
intent,somearemisleading.Notunderstandingthesefeatures
canaffecttheextensibilityofyourcodeandmakeitharderto
derivefromyourclasses.Inthischapteryouwilllearnwhatto
avoidandhowtouseotherfeaturesrelatedtoinheritanceand
polymorphism.
MULTITHREADINGGOTCHAS
Creatingathreadiseasy;managingitisanotherstory.Howdo
youtakecareofthreadsafety?Shouldyoucreateyourown
threadoruseathreadfromthethreadpool?Howare
exceptionshandledinmultithreadedapplications?Whatother
issuesdoyouneedtothinkaboutwhencreatinga.NET
multithreadedapplication?Thischapterwillhelpyou
understandthefundamentalissuesthatcanmakeadifference
betweenthesuccessorfailureofamultithreadedapplication.
COM-INTEROPANDENTERPRISESERVICESGOTCHAS
Ifyouhavetoworkwithlegacycode,.NETandCOM
interoperabilityisofinteresttoyou.TheCOM-Interopfacilities
providedin.NETmakethistaskalmostseamless,andputtingit
touseappearsprettysimple.However,touseCOM-Interop
correctly,youneedsomeforethoughtandplanning.Ifyouthink
usingaCOMcomponentfrom.NETissimple,thinkagain.You
needtofullyunderstandissuesrelatedtotheapartmentofthe
thread,theresourcecleanup,andthelayeringofyour
application.Howdoyouexposeyour.NETcomponentsforCOM
interoperability?ShouldyoujustturnontheVisualStudio
settingstoregisterthetypelibrary?Whatdoyouneedtodoto
makethiseffective?Inthischapteryouwilllearnhowto
effectivelyinteroperatebetween.NETandCOM.
WhatYouNeedtoUseThisBook
Idevelopedthegotchasinthisbookthroughmyexplorationsof
.NETFramework1.1andthelanguageversions,tools,and
compilersthataccompanyit,allofwhichareavailableinany
edition(beyondtheStandardEdition)ofVisualStudio2003.
YouwillneedVisualStudio2003and.NETFramework1.1to
runmyexamples.Ihavealsotestedeachofthegotchaswith
.NET2.0Beta1(a.k.a.Whidbey)andhavenotedanychanges
inbehavior.Ifyouareusingalater.NET2.0Beta,your
experiencemaydifferfrommine,dependingonthebuild
versionyouareusing.Commentson.NET2.0arebasedon
Beta1,whichissubjecttochange.Ithinkitisinappropriateto
commentonthebehaviorofaproductwhileitisinBeta1,soI
havenotaddedanynewgotchasspottedwhenworkingwith
.NET2.0Beta1.
MeasureofPerformance
Occasionally,Icomparethespeedofexecutionofacode
examplewiththespeedofexecutionofanalternativewayof
implementingthesamelogic.Theperformancecomparisonis
simplyempiricalandhasbeendoneonaDellLatitudeC640
witha2GHZPentium4processor,512MBofRAM,anda40GB
harddriverunningWindowsServer2003StandardEdition.In
runningthesecomparisons,IusedVisualStudio.NET2003with
.NET1.1.Nothingelseintensivewasbeingexecutedwhile
measuringtheperformance.
ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Plaintext
Indicatesmenutitles,menuoptions,menubuttons,and
keyboardaccelerators(suchasAltandCtrl).
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,directories,andUnixutilities.
Constantwidth
Indicatescommands,options,switches,variables,
attributes,keys,functions,types,classes,namespaces,
methods,modules,properties,parameters,values,objects,
events,eventhandlers,XMLtags,HTMLtags,macros,the
contentsoffiles,ortheoutputfromcommands.
Constantwidthbold
Showscommandsorothertextthatshouldbetyped
literallybytheuser.
Constantwidthitalic
Showstextthatshouldbereplacedwithuser-supplied
values.
Thisiconsignifiesatip,suggestion,orgeneral
note.
Thisiconindicatesawarningorcaution.
Severalcodeexamplesusedinthisbookillustrateerrorsor
problems,andarenotintendedtobeusedas-is.Toremind
readersofthis,Ihavemarkedthose"gotcha"codeexamples
witha inthecodeheading.Usable,gotcha-freecodeis
markedwitha .
I'vealsoprovidedseveralbibliographicresourcesinthe
Appendix.Whenreferringtothesesourcesinthemaintext,I
havebracketedtheauthornamesasacitation.Seethe
Appendixforfullbibliographicinformation.
UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:".NETGotchasbyVenkatSubramaniam.Copyright
2005O'ReillyMedia,Inc.,0-596-00909-7."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat
CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:
Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:
Safari®Enabled
WhenyouseeaSafari®Enabledicononthecoverof
yourfavoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.
Acknowledgments
WhenIreadsingle-authoredbooks,Iusuallyvisualizethe
authortalkingtome.SinceIstartedworkingonthisbook,that
imagehaschanged;Ivisualizenotjusttheauthor,butateam.
Irealizenowthatagreatdealofteamworkgoesintoit!Some
brightpeoplefromFrance,California,Massachusetts,
Tennessee,Texas,andVirginiacontributedtothisbook.
Iamamazedtoseehowthingshaveprogressedsincethe
thoughtofwritingthisbookgotintomyheadonehotsummer
afternoonlastyear.IwouldfirstliketothankBruceTateand
MichaelLoukidesforconnectingthedotsandputtingmein
touchwithO'Reilly.ThankstoJohnOsbornofO'Reillyforhis
encouragementandspearheadingthedevelopmentofthis
book.Ilikehishighexpectationsforqualityandemphasison
coveragetomeettheneedsofJavaandC++programmers.
Thisbookwouldhavebeenhardtoreadandtakenalotmore
timetogetoutifnotfortheincredibleeffortofRalphP.Davis
asthedevelopmenteditor.Ralphisdiligent,technical,so
pleasanttoworkwith,andhasagreatsenseofhumor.Iam
amazedathowhemanagedalltheeditsandversionswithout
missingabeatatanytime.ThanksRalph.Iwasalsovery
fortunatetohavetheexpertopinionsofChristopheNassareas
thetechnicaleditor.Anumberofgotchasandexamplesare
betterduetohim.Mercibeaucoup,Christophe.
ThankstoAnthonyMasonforreviewingthebookandofferingto
helpinanywaypossiblewhenheheardIwaswriting.Naresh
Chaudharywasoneoftheearlyreviewersofthebook.Naresh,
thanksfortheimportantroleyouplayedinmakingthisabetter
book.ThankstoChauNguyenandJohnA.Fuquafortaking
timefromtheirverybusyscheduleandprovidingvaluable
input.SpecialthankstoSurendraBhatfornotonlyreviewing
thebook,butforrecommendingothergoodreviewersaswell.I
admireyourquality.IconsiderTedNewardaperfectexampleof
agreatsoftwaredeveloper.Iamveryprivilegedtohavehad
himasoneoftheearlyreviewersofthisbook.ThanksTed!
IwouldliketoexpressmyspecialthankstoBradAbrams,lead
programmanageroftheCLRteamatMicrosoft,forbeingkind
enoughtospendandhourdiscussingthebookwithmeatthe
endofaverylongday.Thecommentsheprovidedafter
reviewingpartsofthebookhavebeenveryvaluable.
ThankstomyfriendSivaThiagarajanwhogavemethewingsto
getintotrainingandmentoring,andpavedthewayformeto
experimentandlearn.IwouldliketothankJayZimmermanfor
providingmeanopportunitytospeakattheNoFluffJustStuff
softwaresymposiumseries,andforencouragingmetowrite.
Youareagoodfriendandmentor.
I'velearntagreatdealfrommystudentsintheindustryandat
theUniversity.I'dliketothankthosewhohavetakenmy
coursesandaskedthoseexcellentquestionstofurthertheir
understandingandmine.
MostofwhatIdohasbeeninfluencedbythehardworkofmy
parents,PadmavathyandRamamurthy.Thankyouboth.Thanks
toProfessorPSK(uncleP.S.Krishnamoorthy)forgettingme
excitedaboutcomputers.Youhavehadmorefar-reaching
influenceonothersthanyourealize.Thankstomydearaunt
anduncle,MythiliandBalu,forshapingme.
Noneofthiswould'vebeenpossiblebutforthesacrificeofmy
family.Thankstomysons,KarthikandKrupakar,forbeingso
patientwhenIhadtohideintheofficeseveralnightsand
weekends.Iamblessedwithincrediblesupportand
encouragementfrommywifeKavitha.Thankyouforyourlove
withoutgotchas!
Chapter1.CLR/FrameworkGotchas
TheCommonLanguageRuntime(CLR)providesacommon
platformfortheexecutionofprogramsin.NET.Thecode
writtenina.NETlanguageisfirsttranslatedintotheMicrosoft
IntermediateLanguage(MSIL).TheCLRthenexecutesthe
MSIL.The.NETFrameworkexposesarichclasslibrarytogive
yourapplicationsaccesstoitsunderlyingcapabilities.
InthischapterIdiscussthefeaturesintheCLRandthe
Frameworkthatcanimpactthebehaviorandperformanceof
yourapplication.Iwillalsodiscussitemsthataresomewhat
confusing,misleading,orpronetomisuse.
Developerscominginto.NETknowingotherlanguagesexpect
behaviorsimilartowhatthey'reusedto.C++andJava
programmersexpectC#toactalmostthesame,sinceitlooks
almostthesame.VB6programmershavelikeexpectationsof
VB.NET.
However,whenitcomestothealiasesfordatatypes,andthe
behaviorofvaluetypesversusreferencetypes,.NEThasafew
surprises.Furthermore,somefeaturesmaybeconvenientto
use,butmaynotprovidethebestperformance.Sufficeittosay
thatwhendealingwitharichbutnewAPI,youneedtoclearly
understanditsbehavior.Idiosyncrasiesoftencostyouprecious
time.
GOTCHA#1Typealiassizedoesn'tmatchwhat
you'refamiliarwith
TheCommonLanguageSpecification(CLS)providesrulesto
enableinteroperationoftypeswrittenindifferentlanguages.
TheCommonTypeSystem(CTS)enablescross-language
integration,typesafety,andhigh-performanceexecutionof
managedcode.However,notalltypessupportedinthe.NET
FrameworkareinteroperableorCLS-compliant.When
developingyourclasslibrary,makesurethetypesyouwrite
andexposeareCLS-compliant.RunyourcodethroughFxCopto
makesureitcomplieswiththeMicrosoft"DesignGuidelinesfor
ClassLibraryDevelopers"(see"OntheWeb"intheAppendix).
AsaconveniencetoC++,Java,andVB6programmers,.NET
languagesprovidealiasesfortheCTSdatatypes,likeintand
longinC#andIntegerandLonginVB.NET[Albahari02,
Drayton03,Evjen04,Hamilton03,Robinson04,Thai03].The
aliasesappeartomatchdatatypesinthoseotherlanguages,
butsomeofthemostimportantdonot.
Ifyou'reaC++programmer,youmightassumethatalongin
C#correspondstoalonginC++.Ifyou'recomingfromVB6,
youmightthinkthatIntegerandLonginVB.NETareequivalentto
theIntegerandLongyou'reusedtoinVB6.Butinbothcases,
you'dbewrong.
Let'slookatanexample.HowdoImakeanapplicationbeep?
OnepossibilityistousePInvoketocalltheWin32Beep()method.
PInvokeisa.NETfacilitythatallowsmanagedcodetocall
unmanagedfunctionsinDLLs.InVB6,Beep()hasthis
declaration:
Beep(dwFreqasLong,dwDurationasLong)asBoolean