Tải bản đầy đủ (.pdf) (1,100 trang)

2006 aw essential c sharp v2 0

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.01 MB, 1,100 trang )

EssentialC#2.0
ByMarkMichaelis
...............................................
Publisher:AddisonWesleyProfessional
PubDate:July13,2006
PrintISBN-10:0321150775
PrintISBN-13:978-0-321-15077-6
Pages:768

TableofContents|Index

"EssentialC#2.0pullsoffaverydifficulttask.Theearlychaptersarecomprehensibleby
beginningdevelopers,whilethelaterchapterspullnopunchesandprovidethe
experienceddeveloperwiththedetailedinformationtheyneedtomakethemostofC#
2.0.Startingwiththefirstchapter,Markhassuccessfullyinterwoventidbitsofinformation
usefultoeventhemostadvanceddeveloperwhilekeepingthebookapproachable."Chris
Kinsman,chiefarchitect,Vertafore,MicrosoftRegionalDirector
"Howrefreshing!ThisbookdealswithC#thoroughly,ratherthanskimmingoverthewhole
.NETframework.Itisvaluabletonewcomersandprofessionalsalike."JonSkeet,C#MVP
"EssentialC#2.0isaone-stopshopforanexperiencedprogrammerlookingtorampup
ononeofthehottestlanguagesaroundtoday.Markdeliversanintelligentanddetailed
tourofC#,providingnewcomerstothelanguagewithasolidfoundationofskillonwhich
tobuildtheirnextgenerationofapplications."StephenToub,technicaleditor,MSDN
Magazine
"Thisbookprovidescomplete,up-to-datecoverageofalltheprogrammingconstructsin
C#.Masterfullyorganized,itallowsbeginningprogrammerstogetonboardandleads
moreexperiencedprogrammersintotheworldofstructuredprogramming.Becauseofits
unwaveringfocusontheessentialprogrammingconstructsofC#suchasgenerics,
delegates,andmuchmorethisbookisindispensable.Forprogrammerswhowanttosolve
theirday-to-dayprogrammingissuesusingthelatestfeaturesthismodernprogramming
languagehastooffer,thisbookisindispensable."NarendraPoflee,ITintegration


specialist,ItronInc.
"EssentialC#2.0isanidealbookforallprogrammersinterestedinC#.Ifyouarea
beginner,youwillquicklylearnthebasicsofC#programmingandbecomefamiliarwith
theconcepts.Theflowofthetextiseasytofollowanddoesagreatjobofnotrepeating
conceptsthathavealreadybeencovered.Fortheexperiencedprogrammer,thisbookhas
pricelessnuggetsembeddedwithinitspages,makingitagreatreadforprogrammerswho
arealreadyfamiliarwithC#.ThiswillbeabookthatIwillkeepnexttomycomputerfor
yearstocome."MichaelStokesbary,softwareengineer,ItronInc.
EssentialC#2.0isaclear,conciseguidetoC#includingthefeaturesnewtoC#2.0.The


bookclearlypresentsmaterialforbeginnersandexpertsandprovidescontrastsand
comparisonsbetweenC#andotherlanguages.TheC#languageiscovered
comprehensivelyandeachimportantconstructisillustratedwithsuccinctcodeexamples.
Completecodeexamplesareavailableonline.MarkMichaelishasorganizedthematerial
forquickaccess.Graphical"mindmaps"atthebeginningofeachchaptershowwhat
materialiscoveredandhoweachtopicrelatestothewhole.
FollowingtheC#introduction,readerswilllearnabout
C#primitivedatatypes,valuetypes,referencetypes,typeconversions,andarrays
Operatorsandcontrolflow,loops,conditionallogic,andsequentialprogramming
Methods,parameters,exceptionhandling,andstructuredprogramming
Classes,inheritance,structures,interfaces,andobject-orientedprogramming
Well-formedtypes,operatoroverloading,namespaces,andgarbagecollection
Generics,collections,anditerators
Reflection,attributes,anddeclarativeprogramming
Threading,synchronization,andmulti-threadedpatterns
Interoperabilityandunsafecode
TheCommonLanguageInfrastructurethatunderliesC#
C#2.0hasamultitudeofnewfeaturesthatmakethelanguageevenmorepowerful,
productive,andefficient.Thesenewfeaturesarethoroughlycoveredinthisbook.A

separateappendixonC#2.0topicshelpsreadersquicklyfindnewfeaturesofthe
language.
Whetheryou'rejuststartingoutasaprogrammer,areanexperienceddeveloperlookingto
learnC#,orareaseasonedC#programmerinterestedinlearningthenewfeaturesofC#
2.0,EssentialC#2.0givesyoujustwhatyouneedtoquicklygetupandrunningwriting
C#applications.


EssentialC#2.0
ByMarkMichaelis
...............................................
Publisher:AddisonWesleyProfessional
PubDate:July13,2006
PrintISBN-10:0321150775
PrintISBN-13:978-0-321-15077-6
Pages:768

TableofContents|Index














































Copyright
PraiseforEssentialC#2.0
Acknowledgments
AbouttheAuthor
Chapter1.IntroducingC#
Hello,World
C#SyntaxFundamentals
WorkingwithVariables
ConsoleInputandOutput
Comments
CommonIntermediateLanguageandILDASM
Summary
Chapter2.DataTypes
FundamentalNumericTypes
MoreFundamentalTypes
nullandvoid
CategoriesofTypes
NullableModifier
ConversionsbetweenDataTypes
Arrays
Summary
Chapter3.OperatorsandControlFlow
Operators
IntroducingFlowControl


















































































CodeBlocks({})
Scope
BooleanExpressions
BitwiseOperators(<<,>>,|,&,^,~)
ControlFlowStatements,Continued
JumpStatements
C#PreprocessorDirectives
Summary
Chapter4.MethodsandParameters
CallingaMethod
DeclaringaMethod
TheusingDirective
ReturnsandParametersonMain()
Parameters
Recursion

MethodOverloading
BasicErrorHandlingwithExceptions
Summary
Chapter5.Classes
DefiningandInstantiatingaClass
InstanceFields
InstanceMethods
UsingthethisKeyword
AccessModifiers
Constructors
Static
constandreadonlyModifiers
Properties
NestedClasses
PartialClasses
Summary
Chapter6.Inheritance
Derivation
OverridingtheBaseClass
AbstractClasses
EverythingUltimatelyDerivesfromSystem.Object
VerifyingtheUnderlyingTypewiththeisOperator
ConversionUsingtheasOperator
Summary















































































Chapter7.Interfaces
IntroducingInterfaces
PolymorphismthroughInterfaces
InterfaceImplementation
CastingbetweentheImplementingClassandItsInterfaces
MultipleInterfaceInheritance
ImplementingMultipleInheritanceviaInterfaces
Versioning
InterfacesComparedwithClasses
Summary
Chapter8.ValueTypes
Structs
Boxing
Enums
Summary
Chapter9.Well-FormedTypes
OverridingobjectMembers
OperatorOverloading
DefiningNamespaces
XMLComments

GarbageCollection
ResourceCleanup
Summary
Chapter10.ExceptionHandling
MultipleExceptionTypes
CatchingExceptions
GeneralCatchBlock
GuidelinesforExceptionHandling
DefiningCustomExceptions
Summary
Chapter11.Generics
C#withoutGenerics
IntroducingGenericTypes
Constraints
GenericMethods
GenericInternals
Summary
Chapter12.Collections
PrimaryCollectionClasses















































































IntroducingCollectionClassInterfaces
ProvidinganIndexOperator
ReturningNulloranEmptyCollection
Iterators
Summary
Chapter13.DelegatesandEvents
MethodPointers
MulticastDelegatesandtheObserverPattern
Events
Summary
Chapter14.ReflectionandAttributes
Reflection
Attributes
Summary
Chapter15.Multithreading
RunningandControllingaSeparateThread
PassingParameterstoThreads
ThreadPooling
UnhandledExceptions
Synchronization
Summary
Chapter16.MultithreadingPatterns
AsynchronousResultsPattern
BackgroundWorkerPattern
WindowsForms

Summary
Chapter17.PlatformInteroperabilityandUnsafeCode
PlatformInvoke
PointersandAddresses
Summary
Chapter18.TheCommonLanguageInfrastructure
DefiningtheCommonLanguageInfrastructure(CLI)
CLIImplementations
C#CompilationtoMachineCode
Runtime
ApplicationDomains
Assemblies,Manifests,andModules
CommonIntermediateLanguage(CIL)
CommonTypeSystem(CTS)































CommonLanguageSpecification(CLS)
BaseClassLibrary(BCL)
Metadata
Summary
AppendixA.DownloadingandInstallingtheC#CompilerandtheCLIPlatform
Microsoft's.NET
Mono
AppendixB.CompleteSourceCodeListings
Chapters3and4
Chapter9
Chapter12
Chapter14
Chapter17
AppendixC.C#2.0Topics
Index



Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
The.NETlogoiseitheraregisteredtrademarkortrademarkof
MicrosoftCorporationintheUnitedStatesand/orother
countriesandisusedunderlicensefromMicrosoft.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheUnitedStatespleasecontact:
InternationalSales




VisitusontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData:
Michaelis,Mark.
EssentialC#2.0/MarkMichaelis.
p.cm.
Includesindex.
ISBN0-321-15077-5(pbk.:alk.paper)
1.C#(Computerprogramlanguage)I.Title.
QA76.73.C154M5232006
005.13'3dc22
2006009699
Copyright©2007PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.Firstprinting,July2006

Dedication



Tomyfamily:Elisabeth,Benjamin,Hanna,andAbigail.
Microsoft.NETDevelopmentSeries
JohnMontgomery,SeriesAdvisor
DonBox,SeriesAdvisor
MartinHeller,SeriesEditor
TheMicrosoft.NETDevelopmentSeriesissupportedand
developedbytheleadersandexpertsofMicrosoftdevelopment
technologiesincludingMicrosoftarchitectsandDevelopMentor
instructors.Thebooksinthisseriesprovideacoreresourceof
informationandunderstandingeverydeveloperneedsinorder
towriteeffectiveapplicationsandmanagedcode.Learnfrom
theleadershowtomaximizeyouruseofthe.NETFramework
anditsprogramminglanguages.
TitlesintheSeries



BradAbrams,.NETFrameworkStandard
LibraryAnnotatedReferenceVolume1:
BaseClassLibraryandExtended
NumericsLibrary,0-321-15489-4

ChristianNagel,EnterpriseServiceswith
the.NETFramework:Developing
DistributedBusinessSolutionswith.NET
EnterpriseServices,0-321-24673-X

BradAbramsandTamaraAbrams,.NET
FrameworkStandardLibraryAnnotated
Reference,Volume2:NetworkingLibrary,

ReflectionLibrary,andXMLLibrary,0321-19445-4

BrianNoyes,DataBindingwithWindows
Forms2.0:ProgrammingSmartClient
DataApplicationswith.NET,0-32126892-X



FritzOnion,EssentialASP.NETwith
ExamplesinC#,0-201-76040-1

KeithBallinger,.NETWebServices:
ArchitectureandImplementation,0-321-
11359-4



FritzOnion,EssentialASP.NETwith
ExamplesinVisualBasic.NET,0-201-


76039-8
BobBeauchemin,NielsBerglund,Dan
Sullivan,AFirstLookatSQLServer2005
forDevelopers,0-321-18059-3



TedPattisonandDr.JoeHummel,
BuildingApplicationsandComponents

withVisualBasic.NET,0-201-73495-8

DonBoxwithChrisSells,Essential.NET,
Volume1:TheCommonLanguage

Runtime,0-201-73411-7



Dr.NeilRoodyn,eXtreme.NET:
IntroducingeXtremeProgramming
Techniquesto.NETDevelopers,0-32130363-6

KeithBrown,The.NETDeveloper'sGuide

toWindowsSecurity,0-321-22835-9



ChrisSells,WindowsFormsProgramming
inC#,0-321-11620-8

EricCarterandEricLippert,VisualStudio
ToolsforOffice:UsingC#withExcel,

Word,Outlook,andInfoPath,0-32133488-4



ChrisSellsandJustinGehtland,Windows

FormsProgramminginVisualBasic.NET,
0-321-12519-3

EricCarterandEricLippert,VisualStudio
ToolsforOffice:UsingVisualBasic2005

withExcel,Word,Outlook,andInfoPath,
0-321-41175-7



MaheshChand,GraphicsProgramming
withGDI+,0-321-16077-0

PaulVick,TheVisualBasic.NET
ProgrammingLanguage,0-321-16951-4
DamienWatkins,MarkHammond,Brad
Abrams,Programminginthe.NET
Environment,0-201-77018-0


KrzysztofCwalinaandBradAbrams,
FrameworkDesignGuidelines:
Conventions,Idioms,andPatternsfor
Reusable.NETLibraries,0-321-24675-6



ShawnWildermuth,PragmaticADO.NET:
DataAccessfortheInternetWorld,0201-74568-2


PaulYaoandDavidDurant,.NETCompact
FrameworkProgrammingwithC#,0-32117403-8

AndersHejlsberg,ScottWiltamuth,Peter
Golde,TheC#ProgrammingLanguage,

0-321-15491-6



PaulYaoandDavidDurant,.NETCompact
FrameworkProgrammingwithVisual
Basic.NET,0-321-17404-6

AlexHomer,DaveSussman,MarkFussell,
ADO.NETandSystem.Xmlv.2.0TheBeta
Version,0-321-24712-4
AlexHomer,DaveSussman,RobHoward,
ASP.NETv.2.0TheBetaVersion,0-321-
25727-8
JamesS.MillerandSusannRagsdale,The
CommonLanguageInfrastructure

AnnotatedStandard,0-321-15493-2






PraiseforEssentialC#2.0
"EssentialC#2.0pullsoffaverydifficulttask.Theearly
chaptersarecomprehensiblebybeginningdevelopers,
whilethelaterchapterspullnopunchesandprovidethe
experienceddeveloperwiththedetailedinformationthey
needtomakethemostofC#2.0.Startingwiththefirst
chapter,Markhassuccessfullyinterwoventidbitsof
informationusefultoeventhemostadvanceddeveloper
whilekeepingthebookapproachable."
ChrisKinsman,chiefarchitect,Vertafore,Microsoft
RegionalDirector
"Howrefreshing!ThisbookdealswithC#thoroughly,
ratherthanskimmingoverthewhole.NETframework.It
isvaluabletonewcomersandprofessionalsalike."
JonSkeet,C#MVP
"EssentialC#2.0isaone-stopshopforanexperienced
programmerlookingtorampupononeofthehottest
languagesaroundtoday.Markdeliversanintelligentand
detailedtourofC#,providingnewcomerstothelanguage
withasolidfoundationofskillonwhichtobuildtheirnext
generationofapplications."
StephenToub,technicaleditor,MSDNMagazine
"Thisbookprovidescomplete,up-to-datecoverageofall
theprogrammingconstructsinC#.Masterfullyorganized,
itallowsbeginningprogrammerstogetonboardand
leadsmoreexperiencedprogrammersintotheworldof
structuredprogramming.Becauseofitsunwaveringfocus
ontheessentialprogrammingconstructsofC#suchas



generics,delegates,andmuchmorethisbookis
indispensable.Forprogrammerswhowanttosolvetheir
day-to-dayprogrammingissuesusingthelatestfeatures
thismodernprogramminglanguagehastooffer,thisbook
isindispensable."
NarendraPoflee,ITintegrationspecialist,ItronInc.
"EssentialC#2.0isanidealbookforallprogrammers
interestedinC#.Ifyouareabeginner,youwillquickly
learnthebasicsofC#programmingandbecomefamiliar
withtheconcepts.Theflowofthetextiseasytofollow
anddoesagreatjobofnotrepeatingconceptsthathave
alreadybeencovered.Fortheexperiencedprogrammer,
thisbookhaspricelessnuggetsembeddedwithinits
pages,makingitagreatreadforprogrammerswhoare
alreadyfamiliarwithC#.ThiswillbeabookthatIwill
keepnexttomycomputerforyearstocome."
MichaelStokesbary,softwareengineer,ItronInc.

Forward
ForthoseintheindustrywhohavewatchedtheCprogramming
languagedeveloptoembracenewconceptssuchasobject
programming(C++),ubiquityacrossplatforms(Java),and
highlystructuredmodelsthatformthebasisofC#,itisclear
thatthelanguageiswellpositionedtoholditsownasa
dominantdevelopmentlanguage.
Thisbookhaseverythingadeveloperneedstoknowtogetup
andrunningwiththelanguage.Manyconcisecodesamples,the
useofmindmapstoprovidecontext,andtheinterestingway
MarkcontrastsC#withotherlanguagesmakeEssentialC#2.0
standoutinaseaofC#books.

IhaveknownMarkforawhilenow.Hisextensiveinvolvement


inthedevelopmentofC#principles,togetherwithhisprior
experienceasanauthorofbooksonC++,COM+,andC#,
uniquelyqualifyhimtowritethebookthatIbelievewillbea
seminalreferenceforC#.
Further,Mark'steachingexperienceallowshimtocombinethe
worldoftechnicalskillwiththatofpractical,intuitivetutorial.It
beginswithprinciplesofobjectprogramminginC#,asitisa
referencetoverifyadvancedmultithreadingtechniquesina
complexsystem.Thereader,noviceorexpert,willenjoyhis
casualstyleandmethodofeloquentlycommunicating
challengingtopics.
Thisreferenceandtutorialshouldbeontheshelfnexttoyour
workstationandcarriedinyourbackpack.Pickitupandreadit!
Imconfidentthatwhetheryouareneworexperiencedwiththe
language,youwilllearnsomethinginthisbookthatwillinduce
an"aha!"moment!
PrashantSridharan
MicrosoftCorporation
March2006

Preface
Throughoutthehistoryofsoftwareengineering,the
methodologyusedtowritecomputerprogramshasundergone
severalparadigmshifts,eachbuildingonthefoundationofthe
formerbyincreasingcodeorganizationanddecreasing
complexity.Thisbooktakesyouthroughthesesameparadigm
shifts.

Thebeginningchapterstakeyouthroughsequential
programmingstructureinwhichstatementsarewrittenin
theorderinwhichtheyareexecuted.Theproblemwiththis


modelisthatcomplexityincreasesexponentiallyasthe
requirementsincrease.Toreducethiscomplexity,codeblocks
aremovedintomethods,whichcreatesastructured
programmingmodel.Thisallowsyoutocallthesamecode
blockfrommultiplelocationswithinaprogram,without
duplicatingcode.Evenwiththisconstruct,however,programs
quicklybecomeunwieldyandrequirefurtherabstraction.From
thisemergesobject-orientedprogramming,whichChapter5
discusses.Insubsequentchapters,youcontinuetolearnabout
additionalmethodologies,suchasinterface-based
programming,andeventuallyrudimentaryformsofdeclarative
programming(inChapter14)viaattributes.
Thisbookhasthreemainfunctions.
ItprovidescomprehensivecoverageoftheC#language,
goingbeyondatutorialandofferingafoundationupon
whichyoucanbegineffectivesoftwaredevelopment
projects.
ForreadersalreadyfamiliarwithC#,thisbookprovides
insightintosomeofthemorecomplexprogramming
paradigmsandprovidesin-depthcoverageofthefeatures
introducedinthelatestversionofthelanguage,C#2.0.
Itservesasatimelessreference,evenafteryougain
proficiencywiththelanguage.
ThekeytosuccessfullylearningC#istostartcodingassoonas
possible.Don'twaituntilyouarean"expert"intheory;start

writingsoftwareimmediately.Asabelieveriniterative
development,Ihopethisbookenablesevenanovice
programmertobeginwritingbasicC#codebytheendof
Chapter2.
Anumberoftopicsarenotcoveredinthisbook.Youwon'tfind


coverageoftopicssuchasASP.NET,ADO.NET,smartclient
development,distributedprogramming,andsoon.Although
thesetopicsarerelevanttothe.NETframework,todothem
justicerequiresbooksoftheirown.Fortunately,AddisonWesley'sMicrosoft.NETDevelopmentSeriesprovidesawealth
ofwritingonthesetopics.Readingthisbookwillprepareyouto
focusonanddevelopexpertiseinanyoftheseareas.Itfocuses
onC#andthetypeswithintheBaseClassLibrary.

TargetAudienceforThisBook
Mychallengewiththisbookwashowtokeepadvanced
developersawakewhilenotabandoningbeginnersbyusing
wordslike"assembly,""link,""chain,""thread,"and"fusion,"as
ifthetopicwasmoreappropriateforblacksmithsthanfor
programmers.Thisbook'sprimaryaudienceisexperienced
developerslookingtoaddanotherlanguagetotheirquiver.
However,Ihavecarefullyassembledthisbooktoprovide
significantvaluetodevelopersatalllevels.
Beginners:Ifyouarenewtoprogramming,thisbookserves
asaresourcetohelptransitionyoufromanentry-level
programmertoaC#developer,comfortablewithanyC#
programmingtaskthat'sthrownyourway.Thisbooknot
onlyteachesyousyntax,butitalsotrainsyouingood
programmingpracticesthatwillserveyouthroughoutyour

programmingcareer.
Structuredprogrammers:Justasit'sbesttolearnaforeign
languagethroughimmersion,learningacomputerlanguage
ismosteffectivewhenyoubeginusingitbeforeyouknow
alltheintricacies.Inthisvein,thebookbeginswitha
tutorialthatwillbecomfortableforthosefamiliarwith
structuredprogramming,andbytheendofChapter4,
developersinthiscategoryshouldfeelathomewriting
basiccontrolflowprograms.However,thekeytoexcellence


forC#developersisnotmemorizingsyntax.Totransition
fromsimpleprogramstoenterprisedevelopment,theC#
developermustthinknativelyintermsofobjectsandtheir
relationships.Tothisend,Chapter5'sBeginnerTopics
introduceclassesandobject-orienteddevelopment.Therole
ofhistoricallystructuredprogramminglanguagessuchasC,
COBOL,andFORTRANisstillsignificantbutshrinking,soit
behoovessoftwareengineerstobecomefamiliarwith
object-orienteddevelopment.C#isanideallanguagefor
makingthistransitionbecauseitwasdesignedwithobjectorienteddevelopmentasoneofitscoretenets.
Object-basedandobject-orienteddevelopers:C++and
Javaprogrammers,andmanyexperiencedVisualBasic
programmers,fallintothiscategory.Manyofyouare
alreadycompletelycomfortablewithsemicolonsandcurly
braces.AbriefglanceatthecodeinChapter1revealsthat
atitscore,C#issimilartotheCandC++stylelanguages
thatyoualreadyknow.
C#professionals:ForthosealreadyversedinC#,thisbook
providesaconvenientreferenceforlessfrequently

encounteredsyntax.Furthermore,itprovidesanswersto
languagedetailsandsubtletiesseldomaddressed.Most
importantly,itpresentstheguidelinesandpatternsfor
programmingrobustandmaintainablecode.Thisbookalso
aidsinthetaskofteachingC#toothers.
WiththeemergenceofC#2.0,someofthemostprominent
enhancementsare:
-Partialclasses(seeChapter5)
-Globalnamespacequalifiers(seeChapter9)
-Differentaccessmodifiersonpropertygettersand
setters(seeChapter5


-Anonymousmethods(seeChapter13)
-Generics(seeChapter11)
-Iteratortopics(seeChapter12)
Thesetopicsarecoveredindetailforthosenotalready
familiarwiththem.AlsopertinenttoadvancedC#
developmentisthesubjectofpointers,inChapter17.Even
experiencedC#developersoftendonotunderstandthis
topicwell.

FeaturesofThisBook
EssentialC#2.0isalanguagebookthatadherestothecore
C#Language2.0Specification.Tohelpyouunderstandthe
variousC#constructs,itprovidesnumerousexamples
demonstratingeachfeature.Accompanyingeachconceptare
guidelinesandbestpractices,ensuringthatcodecompiles,
avoidslikelypitfalls,andachievesmaximummaintainability.
Toimprovereadability,codeisspeciallyformattedandchapters

areoutlinedusingmindmaps.

CodeSamples
Thecodesnippetsinmostofthistextcanrunonany
implementationoftheCommonLanguageInfrastructure(CLI),
includingtheMono,Rotor,andMicrosoft.NETplatforms.
Platform-orvendor-specificlibrariesareseldomused,except
whencommunicatingimportantconceptsrelevantonlytothose
platforms(appropriatelyhandlingthesingle-threadeduser
interfaceofWindows,forexample).Anycodethatspecifically
requiresC#2.0complianceiscalledoutinAppendixC:C#2.0
Topics.


Hereisasamplecodelisting.

Listing1.17.CommentingYourCode

[Viewfullsizeimage]

Theformattingisasfollows.
Commentsareshowninitalics.
/*Displayagreetingtotheconsole
usingcompositeformatting.*/


Keywordsareshowninbold.
staticvoidMain()
Highlightedcodecallsoutspecificcodesnippetsthatmay
havechangedfromanearlierlisting,ordemonstratesthe

conceptdescribedinthetext.
System.Console.Write/*Nonewline*/(
Highlightingcanappearonanentirelineoronjustafew
characterswithinaline.
System.Console.WriteLine(
"Yourfullnameis{0}{1}.",
Incompletelistingscontainanellipsistodenoteirrelevant
codethathasbeenomitted.
//...
Consoleoutputistheoutputfromaparticularlistingthat
appearsfollowingthelisting.

Output1.1.

>HeyYou.exe
Heyyou!
Enteryourfirstname:Inigo
Enteryourlastname:Montoya

Userinputfortheprogramappearsinitalics.
Althoughitmighthavebeenconvenienttoprovidefullcode


samplesthatyoucouldcopyintoyourownprograms,doingso
woulddetractyoufromlearningaparticulartopic.Therefore,
youneedtomodifythecodesamplesbeforeyoucan
incorporatethemintoyourprograms.Thecoreomissioniserror
checking,suchasexceptionhandling.Also,codesamplesdo
notexplicitlyincludeusingSystemstatements.Youneedto
assumethestatementthroughoutallsamples.

Youcanfindsamplecodeat
andat
www.awprofessional.com/title=0321150775.

MindMaps
Eachchapter'sintroductionincludesamindmap,whichserves
asanoutlinethatprovidesat-a-glancereferencetoeach
chapter'scontent.Hereisanexample(takenfromChapter12).

[Viewfullsizeimage]

Thethemeofeachchapterappearsinthemindmap'scenter.
High-leveltopicsspreadoutfromthecore.Mindmapsallow
youtoabsorbtheflowfromhigh-leveltomoredetailed
conceptseasily,withlesschanceofencounteringveryspecific
knowledgethatyoumightnotbelookingfor.


HelpfulNotes
Dependingonyourlevelofexperience,specialcodeblocksand
noteswillhelpyounavigatethroughthetext.
BeginnerTopicsprovidedefinitionsorexplanationstargeted
specificallytowardentry-levelprogrammers.
AdvancedTopicsenableexperienceddeveloperstofocuson
thematerialthatismostrelevanttothem.
Calloutnoteshighlightkeyprinciplesincalloutboxesso
thatreaderseasilyrecognizetheirsignificance.
LanguageContrastsidebarsidentifykeydifferences
betweenC#anditspredecessorstoaidthosefamiliarwith
otherlanguages.


HowThisBookIsOrganized
Atahighlevel,softwareengineeringisaboutmanaging
complexity,anditistowardthisendthatIhaveorganized
EssentialC#2.0.Chapters14introducestructured
programming,whichenableyoutostartwritingsimple
functioningcodeimmediately.Chapters59presenttheobjectorientedconstructsofC#.Novicereadersshouldfocusonfully
understandingthissectionbeforetheyproceedtothemore
advancedtopicsfoundintheremainderofthisbook.
Chapters1113introduceadditionalcomplexity-reducing
constructs,handlingcommonpatternsneededbyvirtuallyall
modernprograms.Thisleadstodynamicprogrammingwith
reflectionandattributes,whichisusedextensivelyforthreading
andinteroperability,thechaptersthatfollow.


ThebookendswithachapterontheCommonLanguage
Infrastructure,whichdescribesC#withinthecontextofthe
developmentplatforminwhichitoperates.Thischapter
appearsattheendbecauseitisnotC#specificanditdeparts
fromthesyntaxandprogrammingstyleintherestofthebook.
However,thischapterissuitableforreadingatanytime,
perhapsmostappropriatelyimmediatelyfollowingChapter1.
Hereisadescriptionofeachchapter.
Chapter1IntroducingC#:AfterpresentingtheC#HelloWorld
program,thischapterproceedstodissectit.Thisshould
familiarizereaderswiththelookandfeelofaC#program
andprovidedetailsonhowtocompileanddebugtheirown
programs.ItalsotouchesonthecontextofaC#program's
executionanditsintermediatelanguage.

Chapter2DataTypes:Functioningprogramsmanipulate
data,andthischapterintroducestheprimitivedatatypesof
C#.Thisincludescoverageoftwotypecategories,value
typesandreferencetypes,alongwithconversionbetween
typesandsupportforarrays.
Chapter3OperatorsandControlFlow:Totakeadvantageof
theiterativecapabilitiesinacomputer,youneedtoknow
howtoincludeloopsandconditionallogicwithinyour
program.ThischapteralsocoverstheC#operators,data
conversion,andpreprocessordirectives.
Chapter4MethodsandParameters:Thischapter
investigatesthedetailsofmethodsandtheirparameters.It
includespassingbyvalue,passingbyreference,and
returningdataviaaparameter.InC#,defaultparameters
arenotsupported,andthischapterexplainswhyandhow
toprovidethesamefunctionality.


×