Tải bản đầy đủ (.pdf) (833 trang)

Học lập trinh C từ cơ bản đến nâng cao

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 (9.74 MB, 833 trang )



C#7.0All-in-OneForDummies®
Publishedby:JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ
07030-5774,www.wiley.com
Copyright©2018byJohnWiley&Sons,Inc.,Hoboken,NewJerseyMedia
andsoftwarecompilationcopyright©2018byJohnWiley&Sons,Inc.All
rightsreserved.
PublishedsimultaneouslyinCanadaNopartofthispublicationmaybe
reproduced,storedinaretrievalsystemortransmittedinanyformorbyany
means,electronic,mechanical,photocopying,recording,scanningor
otherwise,exceptaspermittedunderSections107or108ofthe1976United
StatesCopyrightAct,withoutthepriorwrittenpermissionofthePublisher.
RequeststothePublisherforpermissionshouldbeaddressedtothe
PermissionsDepartment,JohnWiley&Sons,Inc.,111RiverStreet,
Hoboken,NJ07030,(201)748-6011,fax(201)748-6008,oronlineat
/>Trademarks:Wiley,ForDummies,theDummiesManlogo,Dummies.com,
MakingEverythingEasier,andrelatedtradedressaretrademarksor
registeredtrademarksofJohnWiley&Sons,Inc.andmaynotbeused
withoutwrittenpermission.Allothertrademarksarethepropertyoftheir
respectiveowners.JohnWiley&Sons,Inc.isnotassociatedwithany
productorvendormentionedinthisbook.
LIMITOFLIABILITY/DISCLAIMEROFWARRANTY:THE
PUBLISHERANDTHEAUTHORMAKENOREPRESENTATIONSOR
WARRANTIESWITHRESPECTTOTHEACCURACYOR
COMPLETENESSOFTHECONTENTSOFTHISWORKAND
SPECIFICALLYDISCLAIMALLWARRANTIES,INCLUDING
WITHOUTLIMITATIONWARRANTIESOFFITNESSFORA
PARTICULARPURPOSE.NOWARRANTYMAYBECREATEDOR
EXTENDEDBYSALESORPROMOTIONALMATERIALS.THE
ADVICEANDSTRATEGIESCONTAINEDHEREINMAYNOTBE


SUITABLEFOREVERYSITUATION.THISWORKISSOLDWITH
THEUNDERSTANDINGTHATTHEPUBLISHERISNOTENGAGED
INRENDERINGLEGAL,ACCOUNTING,OROTHERPROFESSIONAL
SERVICES.IFPROFESSIONALASSISTANCEISREQUIRED,THE
SERVICESOFACOMPETENTPROFESSIONALPERSONSHOULDBE


SOUGHT.NEITHERTHEPUBLISHERNORTHEAUTHORSHALLBE
LIABLEFORDAMAGESARISINGHEREFROM.THEFACTTHATAN
ORGANIZATIONORWEBSITEISREFERREDTOINTHISWORKAS
ACITATIONAND/ORAPOTENTIALSOURCEOFFURTHER
INFORMATIONDOESNOTMEANTHATTHEAUTHORORTHE
PUBLISHERENDORSESTHEINFORMATIONTHEORGANIZATION
ORWEBSITEMAYPROVIDEORRECOMMENDATIONSITMAY
MAKE.FURTHER,READERSSHOULDBEAWARETHATINTERNET
WEBSITESLISTEDINTHISWORKMAYHAVECHANGEDOR
DISAPPEAREDBETWEENWHENTHISWORKWASWRITTENAND
WHENITISREAD.
Forgeneralinformationonourotherproductsandservices,pleasecontact
ourCustomerCareDepartmentwithintheU.S.at877-762-2974,outsidethe
U.S.at317-572-3993,orfax317-572-4002.Fortechnicalsupport,please
visit />Wileypublishesinavarietyofprintandelectronicformatsandbyprint-ondemand.Somematerialincludedwithstandardprintversionsofthisbook
maynotbeincludedine-booksorinprint-on-demand.Ifthisbookrefersto
mediasuchasaCDorDVDthatisnotincludedintheversionyou
purchased,youmaydownloadthismaterialat
.FormoreinformationaboutWiley
products,visitwww.wiley.com.
LibraryofCongressControlNumber:2017958295
ISBN:978-111-9-42811-4;ISBN978-111-9-42810-7(ebk);ISBNePDF978111-9-42812-1(ebk)



C#7.0All-in-OneForDummies®
Toviewthisbook'sCheatSheet,simplygoto
www.dummies.comandsearchfor“C#7.0All-in-One
ForDummiesCheatSheet”intheSearchbox.
TableofContents
Cover
Introduction
AboutThisBook
FoolishAssumptions
IconsUsedinThisBook
BeyondtheBook
WheretoGofromHere

Book1:TheBasicsofC#Programming
Chapter1:CreatingYourFirstC#Console
Application
GettingaHandleonComputerLanguages,C#,and.NET
CreatingYourFirstConsoleApplication
MakingYourConsoleAppDoSomething
ReviewingYourConsoleApplication
IntroducingtheToolboxTrick

Chapter2:LivingwithVariability—Declaring
Value-TypeVariables
DeclaringaVariable
What’sanint?
RepresentingFractions
HandlingFloating-PointVariables
UsingtheDecimalType:IsItanIntegeroraFloat?



ExaminingtheboolType:IsItLogical?
CheckingOutCharacterTypes
What’saValueType?
Comparingstringandchar
CalculatingLeapYears:DateTime
DeclaringNumericConstants
ChangingTypes:TheCast
LettingtheC#CompilerInferDataTypes

Chapter3:PullingStrings
TheUnionIsIndivisible,andSoAreStrings
PerformingCommonOperationsonaString
ComparingStrings
WhatIfIWanttoSwitchCase?
LoopingthroughaString
SearchingStrings
GettingInputfromtheCommandLine
ControllingOutputManually
FormattingYourStringsPrecisely
StringBuilder:ManipulatingStringsMoreEfficiently

Chapter4:SmoothOperators
PerformingArithmetic
PerformingLogicalComparisons—IsThatLogical?
MatchingExpressionTypesatTrackDownAMate.com

Chapter5:GettingintotheProgramFlow
BranchingOutwithifandswitch

HereWeGoLoop-the-Loop
LoopingaSpecifiedNumberofTimeswithfor
NestingLoops
Don’tgotoPieces

Chapter6:LiningUpYourDuckswithCollections
TheC#Array
ProcessingArraysbyUsingforeach
SortingArraysofData
UsingvarforArrays


LooseningUpwithC#Collections
UnderstandingCollectionSyntax
UsingLists
UsingDictionaries
ArrayandCollectionInitializers
UsingSets
OnNotUsingOld-FashionedCollections

Chapter7:SteppingthroughCollections
IteratingthroughaDirectoryofFiles
IteratingforeachCollections:Iterators
AccessingCollectionstheArrayWay:Indexers
LoopingAroundtheIteratorBlock

Chapter8:BuyingGeneric
WritingaNewPrescription:Generics
ClassyGenerics:WritingYourOwn
RevisingGenerics


Chapter9:SomeExceptionalExceptions
UsinganExceptionalError-ReportingMechanism
ThrowingExceptionsYourself
KnowingWhatExceptionsAreFor
CanIGetanExceptionalExample?
AssigningMultiplecatchBlocks
PlanningYourException-HandlingStrategy
GrabbingYourLastChancetoCatchanException
ThrowingExpressions

Chapter10:CreatingListsofItemswith
Enumerations
SeeingEnumerationsintheRealWorld
WorkingwithEnumerations
CreatingEnumeratedFlags
DefiningEnumeratedSwitches

Book2:Object-OrientedC#Programming


Chapter1:Object-OrientedProgramming—
What’sItAllAbout?
Object-OrientedConcept#1:Abstraction
Object-OrientedConcept#2:Classification
WhyClassify?
Object-OrientedConcept#3:UsableInterfaces
Object-OrientedConcept#4:AccessControl
HowC#SupportsObject-OrientedConcepts


Chapter2:ShowingSomeClass
DefiningaClassandanObject
AccessingtheMembersofanObject
AnObject-BasedProgramExample
DiscriminatingbetweenObjects
CanYouGiveMeReferences?
ClassesThatContainClassesAretheHappiestClassesinthe
World
GeneratingStaticinClassMembers
DefiningconstandreadonlyDataMembers

Chapter3:WeHaveOurMethods
DefiningandUsingaMethod
AMethodExampleforYourFiles
HavingArgumentswithMethods
ReturningValuesafterChristmas
ReturningMultipleValuesUsingTuples

Chapter4:LetMeSayThisaboutthis
PassinganObjecttoaMethod
DefiningMethods
AccessingtheCurrentObject
UsingLocalFunctions

Chapter5:HoldingaClassResponsible
RestrictingAccesstoClassMembers
WhyYouShouldWorryaboutAccessControl
DefiningClassProperties
GettingYourObjectsOfftoaGoodStart—Constructors



TheC#-ProvidedConstructor
ReplacingtheDefaultConstructor
UsingExpression-BodiedMembers

Chapter6:Inheritance:IsThatAllIGet?
ClassInheritance
WhyYouNeedInheritance
InheritingfromaBankAccountClass(aMoreComplexExample)
IS_AversusHAS_A—I’mSoConfused_A
WhentoIS_AandWhentoHAS_A
OtherFeaturesThatSupportInheritance
TheobjectClass
InheritanceandtheConstructor
TheUpdatedBankAccountClass

Chapter7:Poly-what-ism?
OverloadinganInheritedMethod
Polymorphism
TheClassBusinessCard:ToString()
C#DuringItsAbstractPeriod
SealingaClass

Chapter8:InterfacingwiththeInterface
IntroducingCAN_BE_USED_AS
KnowingWhatanInterfaceIs
UsinganInterface
UsingtheC#PredefinedInterfaceTypes
LookingataProgramThatCAN_BE_USED_ASanExample
UnifyingClassHierarchies

HidingBehindanInterface
InheritinganInterface
UsingInterfacestoManageChangeinObject-Oriented
Programs

Chapter9:DelegatingThoseImportantEvents
E.T.,PhoneHome—TheCallbackProblem
DefiningaDelegate
PassMetheCode,Please—Examples


AMoreReal-WorldExample
Shh!KeepItQuiet—AnonymousMethods
StuffHappens—C#Events

Chapter10:CanIUseYourNamespaceinthe
Library?
DividingaSingleProgramintoMultipleSourceFiles
DividingaSingleProgramintoMultipleAssemblies
PuttingYourClassesintoClassLibraries
GoingBeyondPublicandPrivate:MoreAccessKeywords
PuttingClassesintoNamespaces

Chapter11:ImprovingProductivitywithNamed
andOptionalParameters
ExploringOptionalParameters
LookingatNamedParameters
DealingwithOverloadResolution
UsingAlternativeMethodstoReturnValues


Chapter12:InteractingwithStructures
ComparingStructurestoClasses
CreatingStructures
UsingStructuresasRecords

Book3:DesigningforC#
Chapter1:WritingSecureCode
DesigningSecureSoftware
BuildingSecureWindowsApplications
BuildingSecureWebFormsApplications
UsingSystem.Security

Chapter2:AccessingData
GettingtoKnowSystem.Data
HowtheDataClassesFitintotheFramework
GettingtoYourData
UsingtheSystem.DataNamespace

Chapter3:FishingtheFileStream


GoingWheretheFishAre:TheFileStream
StreamWritingforOldWalter
PullingThemOutoftheStream:UsingStreamReader
MoreReadersandWriters
ExploringMoreStreamsthanLewisandClark

Chapter4:AccessingtheInternet
GettingtoKnowSystem.Net
HowNetClassesFitintotheFramework

UsingtheSystem.NetNamespace

Chapter5:CreatingImages
GettingtoKnowSystem.Drawing
HowtheDrawingClassesFitintotheFramework
UsingtheSystem.DrawingNamespace

Chapter6:ProgrammingDynamically!
ShiftingC#TowardDynamicTyping
EmployingDynamicProgrammingTechniques
PuttingDynamictoUse
RunningwiththeDynamicLanguageRuntime

Book4:ATourofVisualStudio
Chapter1:GettingStartedwithVisualStudio
VersioningtheVersions
InstallingVisualStudio
BreakingDowntheProjects

Chapter2:UsingtheInterface
DesigningintheDesigner
PanelingtheStudio
CodingintheCodeEditor
UsingtheToolsoftheTrade
UsingtheDebuggerasanAidtoLearning

Chapter3:CustomizingVisualStudio
SettingOptions
UsingSnippets



HackingtheProjectTypes

Book5:WindowsDevelopmentwithWPF
Chapter1:IntroducingWPF
UnderstandingWhatWPFCanDo
IntroducingXAML
DivingIn!CreatingYourFirstWPFApplication
WhateverXAMLCanDo,C#CanDoBetter!

Chapter2:UnderstandingtheBasicsofWPF
UsingWPFtoLayOutYourApplication
ArrangingElementswithLayoutPanels
ExploringCommonXAMLControls

Chapter3:DataBindinginWPF
GettingtoKnowDependencyProperties
ExploringtheBindingModes
InvestigatingtheBindingObject
Editing,Validating,Converting,andVisualizingYourData
FindingOutMoreaboutWPFDataBinding

Chapter4:PracticalWPF
CommandingAttention
UsingBuilt-InCommands
UsingCustomCommands
UsingRoutedCommands

Book6:WebDevelopmentwithASP.NET
Chapter1:LookingatHowASP.NETWorkswith

C#
BreakingDownWebApplications
QuestioningtheClient
DealingwithWebServers

Chapter2:BuildingWebApplications
WorkinginVisualStudio
DevelopingwithStyle


Chapter3:ControllingYourDevelopment
Experience
ShowingStufftotheUser
GettingSomeInputfromtheUser
DataBinding
StylingYourControls
MakingSuretheSiteIsAccessible
ConstructingUserControls

Chapter4:Leveragingthe.NETFramework
SurfingWebStreams
SecuringASP.NET
ManagingFiles
BakingCookies
TracingwithTraceContext
NavigatingwithSiteMaps

AbouttheAuthor
AdvertisementPage
ConnectwithDummies

EndUserLicenseAgreement


Introduction
C#isanamazinglanguage!Youcanusethissinglelanguagetodoeverything
fromdesktopdevelopmenttocreatingwebapplicationsandevenweb-based
applicationprogramminginterfaces(APIs).Whileotherdevelopershaveto
overcomedeficienciesintheirlanguagestocreateevenasubsetofthe
applicationtypesthatC#supportswithaplomb,youcanbecodingyour
application,testing,andthensittingonthebeachenjoyingthefruitsofyour
efforts.Ofcourse,anylanguagethatdoesthismuchrequiresabitof
explanation,andC#7.0All-in-OneForDummiesisyourdoorwaytothisnew
adventureindevelopment.
So,whydoyouneedC#7.0All-in-OneForDummiesspecifically?Thisbook
stresseslearningthebasicsoftheC#languagebeforeyoudoanythingelse.
Withthisinmind,thebookbeginswithalltheC#basicsinBooks1through
3,helpsyougetVisualStudio2017installedinBook4,andthentakesyou
throughmoreadvanceddevelopmenttasks,includingbasicweb
development,inBooks5through6.Usingthisbookhelpsyougetthemost
youcanfromC#7.0intheleastpossibletime.

AboutThisBook
EvenifyouhavepastexperiencewithC#,thenewfeaturesinC#7.0will
haveyouproducingfeature-richapplicationsinanevenshortertimethanyou
mayhavebefore.C#7.0All-in-OneForDummiesintroducesyoutoallthese
newfeatures.Forexample,youdiscoverthenewpattern-matchingtechniques
thatC#7.0provides.Youalsodiscoverthewondersofusingtuplesandlocal
functions.Eventheuseofliteralshasimproved,butyou’llhavetolook
insidetofindouthow.ThisparticularbookisdesignedtomakeusingC#7.0
fastandeasy;itremovesthecomplexitythatyoumayhaveexperiencedwhen

tryingtolearnaboutthesetopicsonline.
Tohelpyouabsorbtheconcepts,thisbookusesthefollowingconventions:
Textthatyou’remeanttotypejustasitappearsinthebookisinbold.
Theexceptioniswhenyou’reworkingthroughasteplist:Becauseeach
stepisbold,thetexttotypeisnotbold.


Wordsforyoutotypethatarealsoinitalicsaremeantasplaceholders;
youneedtoreplacethemwithsomethingthatworksforyou.For
example,ifyousee“TypeYourNameandpressEnter,”youneedto
replaceYourNamewithyouractualname.
IalsouseitalicsfortermsIdefine.Thismeansthatyoudon’thavetorely
onothersourcestoprovidethedefinitionsyouneed.
Webaddressesandprogrammingcodeappearinmonofont.Ifyou’re
readingadigitalversionofthisbookonadeviceconnectedtothe
Internet,youcanclickthelivelinktovisitawebsite,likethis:
www.dummies.com.
Whenyouneedtoclickcommandsequences,youseethemseparatedbya
specialarrow,likethis:File  ⇒  NewFile,whichtellsyoutoclickFileand
thenclickNewFile.

FoolishAssumptions
YoumighthaveahardtimebelievingthatI’veassumedanythingaboutyou
—afterall,Ihaven’tevenmetyouyet!Althoughmostassumptionsare
indeedfoolish,Imadecertainassumptionstoprovideastartingpointforthe
book.
ThemostimportantassumptionisthatyouknowhowtouseWindows,have
acopyofWindowsproperlyinstalled,andarefamiliarwithusingWindows
applications.Ifinstallinganapplicationisstillamysterytoyou,youmight
findthisbookabithardtouse.Whilereadingthisbook,youneedtoinstall

applications,discoverhowtousethem,andcreatesimpleapplicationsof
yourown.
YoualsoneedtoknowhowtoworkwiththeInternettosomedegree.Many
ofthematerials,includingthedownloadablesource,appearonline,andyou
needtodownloadtheminordertogetthemaximumvaluefromthebook.In
addition,Book6assumesthatyouhaveacertainknowledgeoftheInternet
whenworkingthroughweb-basedapplicationsandweb-basedservices.

IconsUsedinThisBook
Asyoureadthisbook,youencountericonsinthemarginsthatindicate


materialofspecialinterest(ornot,asthecasemaybe!).Here’swhatthe

iconsmean:
Tipsarenicebecausetheyhelpyousavetimeorperform
sometaskwithoutalotofextrawork.Thetipsinthisbookaretimesaving
techniquesorpointerstoresourcesthatyoushouldtrysothatyoucangetthe
maximumbenefitwhenperformingC#-relatedtasks.

Idon’twanttosoundlikeanangryparentorsomekindofmaniac,
butyoushouldavoiddoinganythingthat’smarkedwithaWarningicon.
Otherwise,youmightfindthatyourconfigurationfailstoworkas
expected,yougetincorrectresultsfromseeminglybulletproof
processes,or(intheworst-casescenario)youlosedata.

Wheneveryouseethisicon,thinkadvancedtiportechnique.You
mightfindthesetidbitsofusefulinformationjusttooboringforwords,
ortheycouldcontainthesolutionyouneedtogetaC#application
running.Skipthesebitsofinformationwheneveryoulike.


Ifyoudon’tgetanythingelseoutofaparticularchapterorsection,
rememberthematerialmarkedbythisicon.Thistextusuallycontainsan
essentialprocessorabitofinformationthatyoumustknowtowork
withC#.

BeyondtheBook
Thisbookisn’ttheendofyourC#learningexperience—it’sreallyjustthe
beginning.JohnMuellerprovidesonlinecontenttomakethisbookmore
flexibleandbetterabletomeetyourneeds.Also,youcansendJohnemail.
He’lladdressyourbook-specificquestionsandtellyouhowupdatestoC#or


itsassociatedadd-onsaffectbookcontentthroughblogposts.Herearesome
coolonlineadditionstothisbook:
Cheatsheet:Yourememberusingcribnotesinschooltomakeabetter
markonatest,don’tyou?Youdo?Well,acheatsheetissortoflikethat.
Itprovidesyouwithsomespecialnotesabouttasksthatyoucandowith
C#thatnoteveryotherpersonknows.Tofindthecheatsheetforthis
book,gotowww.dummies.comandsearchforC#7.0All-in-OneFor
DummiesCheatSheet.Itcontainsreallyneatinformationsuchashowto
figureoutwhichtemplateyouwanttouse.
Updates:Sometimeschangeshappen.Forexample,Imightnothave
seenanupcomingchangewhenIlookedintomycrystalballduringthe
writingofthisbook.Inthepast,thispossibilitysimplymeantthatthe
bookbecameoutdatedandlessuseful,butyoucannowfindupdatesto
thebookatwww.dummies.com.
Inadditiontotheseupdates,checkouttheblogpostswithanswersto
readerquestionsanddemonstrationsofusefulbook-relatedtechniquesat
/>Companionfiles:Hey!Whoreallywantstotypeallthecodeinthebook

manually?Mostreadersprefertospendtheirtimeactuallyworkingwith
C#,creatingamazingnewapplicationsthatchangetheworld,andseeing
theinterestingthingstheycando,ratherthantyping.Fortunatelyforyou,
theexamplesusedinthebookareavailablefordownload,soallyouneed
todoisreadthebooktolearnC#developmenttechniques.Youcanfind
thesefilesatwww.dummies.com.YoucanalsodownloadOnlineChapters
1–7.Tofindthesourcecodeandonlinechapters,searchthisbook’stitle
atwww.dummies.comandlocatetheDownloadstabonthepagethat
appears.

WheretoGofromHere
AnyonewhoisunfamiliarwithC#shouldstartwithBook1,Chapter1and
movefromtheretotheendofthebook.Thisbookisdesignedtomakeiteasy
foryoutodiscoverthebenefitsofusingC#fromtheoutset.Later,after
you’veseenenoughC#code,youcaninstallVisualStudioandthentrythe
programmingexamplesfoundinthefirstthreeminibooks.


ThisbookassumesthatyouwanttoseeC#codefromtheoutset.However,if
youwanttointeractwiththatcode,youreallyneedtohaveacopyofVisual
Studio2017installed.(SomeexampleswillnotworkatallwitholderVisual
Studioversions.)Withthisinmind,youmaywanttoskiprighttoBook4to
discoverhowtogetyourowncopyofVisualStudio2017.Tohelpensurethat
everyonecanparticipate,thisbookfocusesonthefeaturesofferedbyVisual
Studio2017CommunityEdition,whichisafreedownload.That’sright,you
candiscoverthewondersofC#7.0withoutpayingadime!
ThemoreyouknowaboutC#,thefurtheryoucanstartinthebook.Ifall
you’rereallyinterestedinisanupdateofyourexistingskills,checkoutBook
1,Chapter1todiscoverthechangesinC#.Then,scanthefirstthree
minibookslookingforpointsofinterest.InstallC#byusingtheinstructions

inBook4,Chapter1,andthenmoveontowardtheadvancedtechniques
foundinlaterchapters.


Book1

TheBasicsofC#Programming


ContentsataGlance
Chapter1:CreatingYourFirstC#ConsoleApplication
GettingaHandleonComputerLanguages,C#,and.NET
CreatingYourFirstConsoleApplication
MakingYourConsoleAppDoSomething
ReviewingYourConsoleApplication
IntroducingtheToolboxTrick

Chapter2:LivingwithVariability—DeclaringValue-Type
Variables
DeclaringaVariable
What’sanint?
RepresentingFractions
HandlingFloating-PointVariables
UsingtheDecimalType:IsItanIntegeroraFloat?
ExaminingtheboolType:IsItLogical?
CheckingOutCharacterTypes
What’saValueType?
Comparingstringandchar
CalculatingLeapYears:DateTime
DeclaringNumericConstants

ChangingTypes:TheCast
LettingtheC#CompilerInferDataTypes

Chapter3:PullingStrings
TheUnionIsIndivisible,andSoAreStrings
PerformingCommonOperationsonaString
ComparingStrings
WhatIfIWanttoSwitchCase?
LoopingthroughaString
SearchingStrings
GettingInputfromtheCommandLine
ControllingOutputManually
FormattingYourStringsPrecisely


StringBuilder:ManipulatingStringsMoreEfficiently

Chapter4:SmoothOperators
PerformingArithmetic
PerformingLogicalComparisons—IsThatLogical?
MatchingExpressionTypesatTrackDownAMate.com

Chapter5:GettingintotheProgramFlow
BranchingOutwithifandswitch
HereWeGoLoop-the-Loop
LoopingaSpecifiedNumberofTimeswithfor
NestingLoops
Don’tgotoPieces

Chapter6:LiningUpYourDuckswithCollections

TheC#Array
ProcessingArraysbyUsingforeach
SortingArraysofData
UsingvarforArrays
LooseningUpwithC#Collections
UnderstandingCollectionSyntax
UsingLists
UsingDictionaries
ArrayandCollectionInitializers
UsingSets
OnNotUsingOld-FashionedCollections

Chapter7:SteppingthroughCollections
IteratingthroughaDirectoryofFiles
IteratingforeachCollections:Iterators
AccessingCollectionstheArrayWay:Indexers
LoopingAroundtheIteratorBlock

Chapter8:BuyingGeneric
WritingaNewPrescription:Generics
ClassyGenerics:WritingYourOwn
RevisingGenerics

Chapter9:SomeExceptionalExceptions


UsinganExceptionalError-ReportingMechanism
ThrowingExceptionsYourself
KnowingWhatExceptionsAreFor
CanIGetanExceptionalExample?

AssigningMultiplecatchBlocks
PlanningYourException-HandlingStrategy
GrabbingYourLastChancetoCatchanException
ThrowingExpressions

Chapter10:CreatingListsofItemswithEnumerations
SeeingEnumerationsintheRealWorld
WorkingwithEnumerations
CreatingEnumeratedFlags
DefiningEnumeratedSwitches


Chapter1

CreatingYourFirstC#Console
Application
INTHISCHAPTER
Gettingaquickintroductiontoprogramming
Creatingasimpleconsoleapplication
Examiningtheconsoleapplication
Savingcodeforlater


Thischapterexplainsalittlebitaboutcomputers,computerlanguages—
includingthecomputerlanguageC#(pronounced“seesharp”)—andVisual
Studio2017.YouthencreateasimpleprogramwritteninC#.

GettingaHandleonComputer
Languages,C#,and.NET
Acomputerisanamazinglyfastbutincrediblystupidservant.Computers

willdoanythingyouaskthemto(withinreason);theydoitextremelyfast—
andthey’regettingfasterallthetime.
Unfortunately,computersdon’tunderstandanythingthatresemblesahuman
language.Oh,youmaycomebackatmeandsaysomethinglike,“Hey,my
telephoneletsmedialmyfriendbyjustspeakinghisname.”Yes,atiny
computerrunsyourtelephone.SothatcomputerspeaksEnglish.Butthat’sa
computerprogramthatunderstandsEnglish,notthecomputeritself.
Thelanguagethatcomputerstrulyunderstandismachinelanguage.It’s
possible,butextremelydifficultanderrorprone,forhumanstowritemachine
language.


Humansandcomputershavedecidedtomeetsomewhereinthemiddle.
Programmerscreateprogramsinalanguagethatisn'tnearlyasfreeashuman
speech,butit'salotmoreflexibleandeasiertousethanmachinelanguage.
Thelanguagesoccupyingthismiddleground—C#,forexample—arehighlevelcomputerlanguages.(Highisarelativetermhere.)

What’saprogram?
Whatisaprogram?Inapracticalsense,aWindowsprogramisanexecutable
filethatyoucanrunbydouble-clickingitsicon.Forexample,Microsoft
Word,theeditorusedtowritethisbook,isaprogram.Youcallthatan
executableprogram,orexecutableforshort.Thenamesofexecutable
programfilesgenerallyendwiththeextension.exe.Word,forexample,is
Winword.exe.
Butaprogramissomethingelseaswell.Anexecutableprogramconsistsof
oneormoresourcefiles.AC#sourcefile,forinstance,isatextfilethat
containsasequenceofC#commands,whichfittogetheraccordingtothe
lawsofC#grammar.Thisfileisknownasasourcefile,probablybecauseit’s
asourceoffrustrationandanxiety.
Uh,grammar?There’sgoingtobegrammar?JusttheC#kind,whichismuch

easierthanthekindmostpeoplestruggledwithinjuniorhighschool.

What’sC#?
TheC#programminglanguageisoneofthoseintermediatelanguagesthat
programmersusetocreateexecutableprograms.C#combinestherangeof
thepowerfulbutcomplicatedC++(pronounced“seeplusplus”)withtheease
ofuseofthefriendlybutmoreverboseVisualBasic.(VisualBasic’snewer
.NETincarnationisalmostonparwithC#inmostrespects.Astheflagship
languageof.NET,C#tendstointroducemostnewfeaturesfirst.)AC#
programfilecarriestheextension.cs.
SomepeoplehavepointedoutthatCsharpandDflatarethesamenote,but
youshouldn'trefertothisnewlanguageas“Dflat”withinearshotof
Redmond,Washington.
C#is
Flexible:C#programscanexecuteonthecurrentmachine,ortheycanbe
transmittedoverthewebandexecutedonsomedistantcomputer.


Powerful:C#hasessentiallythesamecommandsetasC++butwiththe
roughedgesfiledsmooth.
Easiertouse:C#error-proofsthecommandsresponsibleformostC++
errors,soyouspendfarlesstimechasingdownthoseerrors.
Visuallyoriented:The.NETcodelibrarythatC#usesformanyofits
capabilitiesprovidesthehelpneededtoreadilycreatecomplicateddisplay
frameswithdrop-downlists,tabbedwindows,groupedbuttons,scroll
bars,andbackgroundimages,tonamejustafew.

.NETispronounced“dotnet.”
Internet-friendly:C#playsapivotalroleinthe.NETFramework,
Microsoft’scurrentapproachtoprogrammingforWindows,theInternet,

andbeyond.
Secure:AnylanguageintendedforuseontheInternetmustinclude
serioussecuritytoprotectagainstmalevolenthackers.
Finally,C#isanintegralpartof.NET.

ThisbookisprimarilyabouttheC#language.Ifyourprimarygoalis
touseVisualStudio,programWindows8or10apps,orASP.NET,the
ForDummiesbooksonthosetopicsgowellwiththisbook.Youcanfind
agoodamountofinformationlaterinthisbookonhowtouseC#to
writeWindows,web,andserviceapplications.

What’s.NET?
.NETbeganseveralyearsagoasMicrosoft’sstrategytoopenthewebtomere
mortalslikeyouandme.Today,it’sbiggerthanthat,encompassing
everythingMicrosoftdoes.Inparticular,it’sthenewwaytoprogramfor
Windows.ItalsogivesaC-basedlanguage,C#,thesimple,visualtoolsthat
madeVisualBasicsopopular.
AlittlebackgroundhelpsyouseetherootsofC#and.NET.Internet
programmingwastraditionallyverydifficultinolderlanguagessuchasCand


×