Microsoft®VisualC#2005Unleashed
ByKevinHoffman
...............................................
Publisher:Sams
PubDate:May09,2006
PrintISBN-10:0-672-32776-7
PrintISBN-13:978-0-672-32776-6
Pages:720
TableofContents|Index
SettingthestandardforapremiumC#reference,MicrosoftVisualC#2005Unleashed
providespracticalexamplesforvirtuallyeveryaspectoftheC#programminglanguage.
Thebookisstructuredforprogressivelearning,soitcanbereadcover-to-coverorusedas
acomprehensivereferenceguide.Youwillbeexposedtoeverythingfromlow-level
informationontheGarbageCollectortoadvancedconcepts,suchascreatingapplications
thatuseEnterpriseServices,creatingWebServices,andevenadvancedWindowsGUI.
Chaptersinclude:
ExpressionsandControlStructures
UIControls
CodeAccessSecurity
Remoting
Peer-to-PeerApplications
Microsoft®VisualC#2005Unleashed
ByKevinHoffman
...............................................
Publisher:Sams
PubDate:May09,2006
PrintISBN-10:0-672-32776-7
PrintISBN-13:978-0-672-32776-6
Pages:720
TableofContents|Index
Copyright
AbouttheAuthor
WeWanttoHearfromYou!
ReaderServices
Introduction
PartI:C#2.0Fundamentals
Chapter1.IntroductiontoC#2.0
WhatIsthe.NETFramework?
WorkingwithVariablesinC#2.0
C#BasicSyntax
WhatYouCanDowithC#
Summary
Chapter2.ExpressionsandControlStructures
BranchingandConditionalLogic
LoopingandRepetition
Summary
Chapter3.StringsandRegularExpressions
WorkingwithStrings
WorkingwithRegularExpressions
Summary
Chapter4.ArraysandCollections
WorkingwithArrays
WorkingwithCollections
Summary
Chapter5.Object-OrientedProgramminginC#
Object-OrientedDesign
Object-OrientedProgramming
Summary
Chapter6.IntroductiontoGenerics
OverviewofGenerics
BuildingGenericTypes
UsingGenericCollections
Summary
PartII:.NETFramework2.0Fundamentals
Chapter7.I/OandPersistence
IntroductiontoStreams
IntroductiontoBasicFileI/O
UsingAsynchronousFileI/O
WorkingwithIsolatedStorage
Summary
Chapter8.WorkingwithXML
ReadingandWritingXMLDocuments
QueryingXMLwithXPath
TransformingDocumentswithXSLT
ValidatingDocumentswithXSD
Summary
Chapter9.EventsandDelegates
IntroductiontoDelegates
UsingAnonymousMethods
CreatingMulticastDelegates
IntroductiontoEvents
AdvancedEvent-BasedProgramming
Summary
Chapter10.MultithreadedProgramming
TheBasicsofThreadedProgramming
WritingYourFirstMultithreadedApplication
DealingwithThreadSynchronizationandContention
UsingtheThreadPoolClass
Summary
Chapter11.ReflectionFundamentals
IntroductiontoReflection
WorkingwithMethodInformation
WorkingwithMemberInformation
ExaminingEvents
CreatingandExaminingCustomCodeAttributes
Summary
Chapter12.AssembliesandAppDomains
IntroductiontoAssemblies
AssembliesUndertheHood
BuildingandUsingAssemblies
StoringandRetrievingAssemblyResources
LocalizationandSatelliteAssemblies
IntroductiontoAppDomains
ProgrammingwithAppDomains
Summary
Chapter13.COMandWindowsInteroperability
IntroductiontoInteroperabilityinC#
UsingCOMObjectsfromthe.NETFramework
Using.NETClassesfromCOM
AccessingCodeinUnmanagedDLLs
Summary
Chapter14.CodeAccessSecurity
IntroductiontoCodeAccessSecurity(CAS)
UsingandAdministeringSecurityPolicy
UsingImperativeSecurity
UsingDeclarativeSecurity
Summary
Chapter15.CryptographyandDataProtection
IntroductiontoCryptography
UsingSecret-KeyEncryption
UsingPublic-KeyEncryption
WorkingwithHashesandDigitalSignatures
UsingtheDataProtectionAPI(DPAPI)
Summary
Chapter16.OptimizingYour.NET2.0Code
UnderstandingBoxingandUnboxing
UsingProperStringManipulationTechniques
EfficientLoopConstruction
SpeedingUpApplicationStartTimes
CodeProfilingUsingthePerformanceWizard
Summary
PartIII:DataAccesswith.NET2.0
Chapter17.ADO.NETFundamentals
IntroductiontoADO.NET
EstablishingaConnection
CommunicatingwiththeDataSource
WorkingwiththeData
Summary
Chapter18.AdvancedADO.NETTechniques
WorkingwiththeNewImprovedDataTable
AccessingDataAsynchronously
UpdatingDatainBatches
UsingtheNewSystem.TransactionsNamespace
Summary
Chapter19.WorkingwithADO.NETDataProviders
IntroductiontoADO.NETDataProviders
UsingProviderFactories
WorkingwithConnectionStrings
EnumeratingDataSources
ObtainingAdditionalProviderInformation
CreatingaCustomADO.NETDataProvider
Summary
Chapter20.StronglyTypedDataSets
IntroductiontotheTypedDataSet
ConnectingTypedDataSetstoLiveData
AnnotatingaTypedDataSet
ExtendingaTypedDataSetUsingPartialClasses
Summary
Chapter21.ProgrammingwithSQLServer2005
IntroductiontotheSQLServer2005CLRHost
BuildingC#StoredProcedures
BuildingC#User-DefinedFunctions
CreatingaC#User-DefinedType
WorkingwiththeNewServer-SideSQLLibrary
UsingMARS(MultipleActiveRecordSets)
Summary
PartIV:DevelopingASP.NET2.0WebApplications
Chapter22.IntroductiontoASP.NET2.0andWebForms
IntroductiontoASP.NET2.0
UnderstandingtheASP.NETPageLifeCycle
OverviewofControlsProvidedbyASP.NET
CreatingandDebuggingASP.NETApplications
HandlingEventsandPostbacks
BuildingInteractiveDynamicPagesUsingClientCallbacks
Summary
Chapter23.StateManagementinASP.NET2.0
WorkingwithApplicationState
WorkingwithSessionState
WorkingwithViewState
StateManagementinWebFarms
Summary
Chapter24.UsingMasterPages
TheWorldBeforeMasterPages
IntroductiontoMasterPages
AdvancedMasterPagesTechniques
Summary
Chapter25.ASP.NETPersonalizationandCustomization
UserInterfaceTailoringwithThemesandSkins
WorkingwithASP.NETUserProfiles
UserCustomizationwithThemesandProfiles
Summary
Chapter26.IntroductiontoWebParts
WebPartBasics
UsingaPersonalizationProvider
BuildingYourFirstWebPartPage
CreatingWebParts
BuildingConnectedWebParts
Summary
Chapter27.BuildingRich,Data-DrivenWebApplications
IntroductiontoDataBindinginASP.NET
UsingData-BoundControls
AdvancedData-BindingTechniques
Summary
Chapter28.SecuringYourASP.NETApplications
SecurityThroughAuthentication
SecurityThroughAuthorization
TheASP.NETSecurityControls
AdvancedASP.NETSecurity
Summary
Chapter29.CreatingCustomASP.NETProviders
TheMembershipProvider
TheRoleProvider
TheProfileProvider
AdditionalProviders
Summary
Chapter30.DevelopingASP.NETControls
BuildingUserControls
CreatingServerControls
ManagingStateWithinServerControls
Summary
Chapter31.ASP.NETManagementandMonitoring
IntroducingtheNewHealthMonitoringSystem
UsingASP.NETPerformanceCounters
Summary
PartV:WebServices
Chapter32.ExposingFunctionalitywithWebServices
IntroductiontoWebServices
CreatingaSimple"HelloWorld"Service
CreatingTransactionalServices
ManagingStateinWebServices
Summary
Chapter33.AdvancedWebServicesProgramming
DesigningforService-OrientedArchitectures(SOA)
UsingWebServiceDiscovery
UsingCustomSOAPHeaders
ProgrammingSecureWebServices
Data-BindingWindowsFormstoWebServices
Summary
PartVI:DevelopingWindowsForms2.0Applications
Chapter34.IntroductiontoWindowsForms2.0
WindowsFormsBasics
CreatingaWindowsFormsApplication
UsingtheWindowsFormsDesigner
ElementsofGoodUserInterfaceDesign
Summary
Chapter35.TheWindowsFormsControlLibrary
TheCommonControlsToolbox
Containers
MenusandToolbars
TheData-RelatedControls
TheComponentsToolboxGroup
ComponentsandControlsforPrinting
DialogComponents
Summary
Chapter36.AdvancedUserInterfaceProgramming
IntroductiontoGDI+
CreatingShapedFormsandControls
UsingVisualInheritance
GlobalizingYourUserInterface
Summary
Chapter37.DataBindingwithWindowsForms2.0
BindingwithTypedDataSets
IntroducingtheBindingSource
UsingtheBindingNavigator
WorkingwiththeDataGridView
DataBindingwithObjects
Parent-DetailBinding
Summary
Chapter38.DevelopingSmartClients
PracticalWebServiceConsumption
UsingtheNewApplicationSettingsSystem
SupportingOfflineandOnlineOperation
AuthorizingandAuthenticatingUsers
MultithreadedWebServiceConsumption
UsingtheBackgroundWorkerControl
Summary
Chapter39.DeployingApplicationsUsingClickOnce
IntroductiontoClickOnce
PublishingClickOnceApplications
UpdatingClickOnceApplications
ProgrammingwiththeSystem.Deployment.ApplicationNamespace
Summary
Chapter40.UsingEnterpriseServices
RegisteringServicedComponents
Just-in-TimeActivationandPooling
QueuedComponents
Role-BasedSecurity
Transactions
SharedProperties
LooselyCoupledEvents
Summary
PartVII:DevelopingEnterpriseandDistributedApplications
Chapter41.Remoting
OverviewofRemoting
WorkingwithRemotingChannels
WorkingwithLifetimeLeases
RemotingwithGenerics
Summary
Index
Copyright
Microsoft®VisualC#2005Unleashed
Copyright©2006bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,
withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2006901231
PrintedintheUnitedStatesofAmerica
FirstPrinting:May2006
090807064321
Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.
MicrosoftisaregisteredtrademarkofMicrosoftCorporation.
WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.Theauthorand
thepublishershallhaveneitherliabilitynorresponsibilitytoany
personorentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbook.
BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales
1-800-382-3419
ForsalesoutsidetheUnitedStates,pleasecontact
InternationalSales
Publisher
PaulBoger
AcquisitionsEditor
NeilRowe
DevelopmentEditor
MarkRenfrow
ProjectEditor
TonyaSimpson
CopyEditor
MargaretBerson
Indexer
KenJohnson
Proofreader
SusanEldridge
TechnicalEditor
J.BoydNolan
PublishingCoordinator
CindyTeeters
InteriorDesigner
GaryAdair
CoverDesigner
AlanClements
Dedication
Writingatechnicalbookinvolvesjustasmuchcreativityand
inspirationaswritingafantasyorasciencefictionnovel;it's
justadifferentkindofinspiration.Iwouldliketodedicatethis
booktomyinspiration:mywonderfulwife,Connie.
Regardlessofwheretheinspirationcomesfromorwhatit
produces,it'sstillahighlycreativeprocessthatissubjectto
writer'sblockandfitsofirritability,crankiness,defeatism,and
beingsoabsorbedinaparticulartopicthattheworldaround
meceasestoexistuntilIhaveconqueredthattopic.
Ittrulyisabattle,"mevs.thetechnology."Theproblemisthat
thisbattlerequiresahugetimeinvestment.Somehowmywife
hasmanagedtotoleratemebeinginthesameroombutsimply
"notbeingthere"whileItypeawayinordertodefeatthe
chaptersthatloombeforeme,daringmetotakethemon.My
daughter,Jerrah,hasherownkeyboardsothatshecan
pretendto"bebusy"justlikeDaddy.There'ssomething
bittersweetaboutthefactthatshewantstobelikeme,butthat
herimpressionofmeisoneofbeingbusyandtypingallthe
time.
Mywife'spatience,love,caring,andsupporthavebeen
invaluable.Withouthersupport,Iwould'vegivenuponwriting
beforeIevengotstarted.AndcertainlywithoutherInever
wouldhavebeenabletowritethisbook,thesinglelargestand
mosttime-consumingbookI'veeverwritten.
Regardlessofwhichdeityyoubelievein,orwhetheryoubelieve
inone,youmustconcedetheexistenceofangels.Afterall,I
ammarriedtoone.
AbouttheAuthor
KevinHoffmanhasbeenprogrammingformorethan20
years.Hegotstartedwhenhisgrandfatherrepairedadiscarded
CommodoreVIC-20andhegotrighttoworkcreatingtextbasedrole-playinggamesinBASIC.Sincethen,hehas
dedicatedhimselftolearningallthereistoknowabout
programming,andusingeveryprogramminglanguagehecould
find,includingPascal,C,C++,Scheme,LISP,ADA,Perl,
Python,Java,andmanyothers.Whenhefirstsawapre-beta
releaseofC#1.0,hewashooked.Heknewatthatmoment
thatthe.NETFrameworkwouldrevolutionizehowdevelopers
createdsoftwareandhowpeopledesignedsoftware,andwould
enablenewtypesofapplicationsandnewfunctionalitythat
eitherusedtobeimpossibleortoocost-prohibitivetoeven
attempt.Asaresultofhispassionforthe.NETFramework,he
hasdubbedhimselfthe".NETAddict."
WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.
AsapublisherforSamsPublishing,Iwelcomeyourcomments.
Youcanemailorwritemedirectlytoletmeknowwhatyoudid
ordidn'tlikeaboutthisbookaswellaswhatwecandotomake
ourbooksbetter.
PleasenotethatIcannothelpyouwithtechnicalproblems
relatedtothetopicofthisbook.WedohaveaUserServices
group,however,whereIwillforwardspecifictechnical
questionsrelatedtothebook.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyourname,emailaddress,andphonenumber.
Iwillcarefullyreviewyourcommentsandsharethemwiththe
authorandeditorswhoworkedonthebook.
Email:
Mail:
PaulBoger
Publisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA
ReaderServices
Visitourwebsiteandregisterthisbookat
www.samspublishing.com/registerforconvenientaccesstoany
updates,downloads,orerratathatmightbeavailableforthis
book.
Introduction
Ifyoucanforceyourselftothinkback10years,thinkaboutthe
proliferationoftechnologyinjustthatshortperiodoftime.
Backinthe"goodole"days,youcouldwalkdownabusycity
street,andyouprobablywouldn'tseeanyonetalkingonacell
phone.Youwouldn'tseepeoplebusilytappingattheirPDAs.
Youdefinitelydidn'tseeanyonesittinginanInternetcaféusing
aTabletPCtosendhand-sketchedapplicationdesignshalfway
aroundtheworldtoaremotedevelopmentteam.
Connectivitybetweenapplicationsandapplicationcomponents
usedtobesomethingthatrequiredtheuseofextremelyskilled,
highlyexpensivedevelopmentefforts.Sure,wehad
technologieslikeCORBA,buttheyhadlimiteduse.
Today,connectivityitselfhasbecomesoubiquitousthatitis
demanded.WhenpeopleturnontheirPDAinanInternetenabledcoffeeshop,theyfullyexpectthattheywillbeableto
connecttotheInternetfromthere.Iftheydon'ttheywill
complaintotheowner.Whenpeopleflipopentheirbrandnew
cellularphone,notonlydotheyexpectittotakephotographs,
buttheyexpecttobeabletouploadtheirphotostoacentral
locationtobesharedwithfriends,family,ortheentireInternet.
Theyexpectthattheycandownloadringtones,games,even
musicandvideos.Iftheycan'ttheywanttheirmoneyback.
Thissamedemandforconnectivity,performance,andmodern
featurescanbefoundindesktopsoftwareandwebsoftwareas
well.Peoplewanttheirapplicationstofollowthe"ItJustWorks"
principle.Theyshouldbeabletobeatonandotherwiseabuse
thatapplicationwithoutfearofretributionintheformoflostor
corrupteddata.UserswanttheirWindowsapplicationstowork
properlywhetherthey'reconnectedtotheInternetornot.They
wanttheirwebapplicationstobemoreresponsivethanthey
usedtobe,theywantthemtolookgreat,andtheywantthem
torunfast,andtheywantthemtorememberwhattheylike,
whattheydon'tlike,andwhotheyare.
Inshort,thedemandsmodernusersareplacingonthequality,
features,andfunctionalityoftheapplicationstheyusehave
neverbeenmorestrict.Programmerstodaymustcreatesome
ofthemostpowerfulapplicationseverwritten,andtheyneedto
doitquickly,reliably,andcheaply.
Thisbookwilltakethedeveloperthroughanin-depth
explorationofthefeatures,power,andcapabilitiesofVisualC#
.NET2005,thelatestandmostpowerfulversionoftheC#
languagerunningonthe.NETFramework2.0.
Amongmanyotherthings,byreadingthisbookyouwill
LearnthefundamentalsoftheC#languageandthecore
featuresofthe.NETFramework2.0,suchasobjectorientedprogramming,generics,andotherbasicssuchas
delegatesandevent-drivenprogramming.
Learnhowtoworkwithdatainmanyformsfrommany
sourcesusingADO.NET2.0,evenhowtowritestored
proceduresforSQLServer2005inC#!
CreateWindowsFormsapplicationswithrich,highly
responsiveuserinterfaces.
DeployWindowsFormsapplicationsfromthewebor
anywhereelsewiththeclickofabutton.
CreateWindowsFormsapplicationsthatupdatethemselves
automaticallyovertheInternetbycheckingfornew
releasesandpatches.
LearnhowtocreateASP.NET2.0applicationsandthenew
featuresthatcomewiththem.
Utilizemasterpages,themes,andskinstocreatea
consistentlookandfeelthroughoutyoursiteandeven
providetheabilityforuserstoselecttheirownstyletheme.
UseWebPartsandWebPartPagestocreatedynamic,usercontrollablecontentpagesthatcontaininformationand
functionalitytargetedtothespecificuserortheuser's
securitylevel.
UsethenewProvidermodelinASP.NETtocreatean
applicationthatcanauthenticateusers,storeuserrole
membership,storeuserprofiledata,anduser
personalizationinformation(suchasWebPartpreferences)
inSQLServer2005in15minutesorless!
Useclientcallbackstocreatehighlyinteractive,Ajax-style
interfacesinASP.NET2.0.
Learnhowtocreatecustom,reusableASP.NETcontrols.
Learnhowtocreateandconsumewebservices.
Useremotingand/orCOM+tocreatedistributed,connected
applications.
Thisbookiscrammedfullofinformationonhowtogetyouup
tospeedonthenewesttechnology.Italsoprovidesyouwith
practicalapplicationofthetechnology.Asweallknow,applying
atechnologyjustbecauseit'sneworinterestingisn't
necessarilytherightthingtodo.Asyoureadthisbook,youwill
beintroducedtothenewtechnologyfromthegroundup
(learningtowalkbeforeyoucanrun),aswellaslearningwhere
thattechnologymakessenseandwhenitshouldbeapplied.
Youmightfindsomeoftheearlierchapterstobesomewhatofa
reviewifyouhavealreadybeenworkingwithC#2005.
However,manyofthelaterchaptersinthebookbuildon
technologiesandtechniquesintroducedinearlierchapters,
makingthisbookideallysuitedtobeingreadfromstartto
finish.
PartI:C#2.0Fundamentals
InThisPart
CHAPTER1IntroductiontoC#2.05
CHAPTER2ExpressionsandControlStructures15
CHAPTER3StringsandRegularExpressions23
CHAPTER4ArraysandCollections33
CHAPTER5Object-OrientedProgramminginC#51
CHAPTER6IntroductiontoGenerics65
Chapter1.IntroductiontoC#2.0
InThisChapter
IntroductiontoC#2.0AtAGlance
WhatIsthe.NETFramework?
WorkingwithVariablesinC#2.0
C#BasicSyntax
WhatYouCanDowithC#
ThischapterprovidesabriefintroductiontotheworldofC#.As
youwillsee,thesyntaxofthelanguageitselfisfairlyeasyto
learn.Thethingthattakesthemosttimeislearninghowto
programonthe.NETFrameworkusingtheC#language.You
willseethebasicsyntaxoftheC#language,includinghowto
declarevariables,createcodeblocks,andofcourse,createyour
first"HelloWorld"application.
IfyoualreadyhaveaworkingknowledgeoftheC#language
fromyourexperiencewithpreviousversions(either1.0or1.1),
youcanskipthischapterandmoveon.Takecarenottoskip
toomanyoftheearlychapters,astherehavebeen
enhancementstothelanguagethatarecoveredearlyoninthe
book,suchasgenericsandanonymousmethods.Thischapter
alsoskipsoversomedetailsthatyoumaynotbeawareofif
youhaveverylittleexposuretoprogramming.Ifyouhave
neverwrittensoftwareontheWindowsplatform(either
WindowsorWeb-based),thisisthewrongchapter,andperhaps
thewrongbook,foryou.
WhatIsthe.NETFramework?
BeforeyoulearnthemechanicsoftheC#languageitself,itis
importantthatyoulearntheevolutionoftechnologiesthat
createdtheneedforalanguagelikeC#.Thissectiontakesyou
onaquicktourofthehistoryofC#,followedbyanexplanation
oftheCommonLanguageRuntime,theCommonTypeSystem,
andconcludingwithanoverviewofgarbage-collected
environments.
TheEvolutionof.NET
Beforethe.NETFrameworkwasreleasedtothepublic,the
majorityofcomponent-orienteddevelopmentfortheWindows
platformtooktheformofCOMobjects.ComponentObject
Model(COM),abinarystandardforcreatingreusable
components,alloweddeveloperstowritecodethatsolved
smallerproblemsinsmallerproblemdomains.Bybreaking
downtheproblemintocomponents,thesolutionoftenbecame
easierandthecomponentsusedtosolvetheproblemcouldbe
reusedtosolveothersimilarproblems.
COMofferedmanyadvantagesanddisadvantages.Oneofthe
mostcommonproblemswiththeCOMstandardwas
appropriatelydubbed"DLLhell."DLLhellarosewhenCOM
interfaceswereindexedintheregistryandthennewerversions
ofthosecomponentswerereleased.Versioningoftencaused
developersheadachesduetothetightlycoupled,binarynature
ofthestandard.Inaddition,ifaDLL'slocationchangedonthe
filesystemwithouttheinformationintheregistrybeing
modified,theCOMinterfacescontainedwithinthatDLLwould
becomeinaccessible.Youcouldseeexamplesofthiswhena
newapplicationwasinstalledwithadifferentversionofsome
sharedcomponent,anditwouldnotonlybreakthenew
application,butallotherapplicationsusingthatcomponentas
well.
Otherproblemswithdevelopmentatthetimeincludedthings
likedifficultymanagingmemory,slowdevelopmenttimes,GUI
controlsthatweretypicallyinsufficientformanytasks,aswell
asalackofinteroperabilitybetweenlanguagessuchasC++
andVisualBasic.
Asasolutiontothisandcountlessotherproblemswith
developmentatthetime,Microsoftbeganworkingonwhatwas
thenreferredtoasCOM+2.0.Thesolutionwouldprovidea
managedenvironmentinwhichcodewouldbeexecutedthat
wouldprovideforenhancedtypesafety,security,andan
incrediblyextensivelibraryofusefulclassesandfunctionsto
makethelivesofdevelopersmucheasier.Eventuallythis
solutionbecamewhatisnowthe.NETFramework.Versions1.0
and1.1havebeenreleasedandnowversion2.0isavailable.In
thenextfewsections,someofthekeyaspectsofthe.NET
Frameworkwillbediscussed:theCommonLanguageRuntime,
theCommonTypeSystem,andtheconceptofgarbagecollectedmanagedcode.
TheCommonLanguageRuntime
BeforetalkingaboutthebasicsofC#,youneedtoknowalittle
bitabouthowC#(andallother.NETlanguages)worksand
whereitsitsinrelationtothevariouscomponentsthatmake
theentire.NETFrameworkrun.
OnesuchcomponentistheCommonLanguageRuntime(almost
exclusivelyreferredtoastheCLR).Unlikepreviousversionsof
C++andsimilarlanguages,C#runsinamanaged
environment.CodethatyouwriteinC#runsinsidethecontext
oftheCommonLanguageRuntime.Theruntimeisresponsible
formanagingthingslikememoryandsecurityandisolating
yourcodefromothercodesothatmaliciousorpoorlywritten
codecan'tinterferewiththenormaloperationofyour
application.
Figure1.1illustratesthelayersof.NET.
Figure1.1.Thelayersof.NET.
[Viewfullsizeimage]
Atthetoplayeryouhavethevarious.NETlanguages(this
figureonlyincludesafewofthelanguagesthatrununderthe
CLR).BeneaththoselanguagesyouhavetheBaseClass
Library.TheBCL(BaseClassLibrary)isthecollectionofclasses
andutilitieswritteninthe.NETFrameworkthatprovideyou
withthefundamentalsyouneedinordertocreateyour
applications,suchascodetoallowyoutodealwithencryption,
dataaccess,fileI/O,webapplications,Windowsapplications,
andmuchmore.Asyouwillseethroughoutthebook,muchof
thetaskoflearningC#isn'tlearningthelanguagesyntax;it's
learningaboutthevastlibraryoftheBCL.Inshort,theCLRis
themanagedexecutionenginethatdrivesthecodewrittenin
theBCLandanyapplicationsyoucreate.
DonBoxhaswrittenanexcellentbookontheCommon
LanguageRuntimethatgivesallthedetailyoucanpossibly
imagineonwhattheCLRisandhowitworks.Thebookiscalled
Essential.NETVolumeI:TheCommonLanguageRuntime