LearnC#InOneDayandLearnItWell
C#forBeginnerswithHands-OnProject
TheonlybookyouneedtostartcodinginC#
immediately
ByJamieChan
/>
Copyright©2015
Allrightsreserved.Nopartofthispublicationmaybereproduced,
distributed,ortransmittedinanyformorbyanymeans,including
photocopying,recording,orotherelectronicormechanicalmethods,without
thepriorwrittenpermissionofthepublisher,exceptinthecaseofbrief
quotationsembodiedincriticalreviewsandcertainothernoncommercialuses
permittedbycopyrightlaw.
Preface
ThisbookiswrittentohelpyoulearnC#FASTandlearnitWELL.
Thebookdoesnotassumeanypriorbackgroundincoding.Ifyouarean
absolutebeginner,you’llfindthatthisbookexplainscomplexconceptsinan
easytounderstandmanner.IfyouareanexperiencedcoderbutnewtoC#,
thisbookwillprovideyouwithenoughdepthtostartcodinginC#
immediately.
Allexamplesinthebookarecarefullychosentodemonstrateeachconceptso
thatyoucangainadeeperunderstandofthelanguage.Topicsarecarefully
selectedtogiveyouabroadexposuretoC#,whilenotoverwhelmingyou
withinformationoverload.Thesetopicsincludeobject-orientedprogramming
concepts,errorhandlingtechniques,filehandlingtechniquesandmore.
Inaddition,asRichardBransonputsit:“Thebestwayoflearningabout
anythingisbydoing”.Thisbookcomeswithaprojectwhereyou’llbeguided
throughthecodingofasimplepayrollsoftwarefromscratch.Theprojectuses
conceptscoveredinthebookandgivesyouachancetoseehowitallties
together.
Youcandownloadthesourcecodefortheprojectandallthesample
programsinthisbookat
/>
ContactInformation
Iwouldlovetohearfromyou.
Forfeedbackorqueries,youcancontactmeat
MoreBooksbyJamie
Python:LearnPythoninOneDayandLearnItWell
CSS:LearnCSSinOneDayandLearnItWell
TableofContents
Chapter1:IntroductiontoC#
WhatisC#?
WhyLearnC#?
Chapter2:GettingreadyforC#
InstallingVisualStudioCommunity
YourFirstC#Program
BasicStructureofaC#Program
Directive
Namespace
TheMain()Method
Comments
Chapter3:TheWorldofVariablesandOperators
Whatarevariables?
DataTypesinC#
int
byte
float
double
decimal
char
bool
NamingaVariable
InitializingaVariable
TheAssignmentSign
BasicOperators
MoreAssignmentOperators
TypeCastingInC#
Chapter4:Arrays,StringsandLists
Array
ArrayPropertiesandMethods
String
StringPropertiesandMethods
Lists
ListPropertiesandMethods
ValueTypevs.ReferenceType
Chapter5:MakingourProgramInteractive
DisplayingMessagestoUsers
EscapeSequences
AcceptingUserInput
ConvertingaStringtoaNumber
PuttingitallTogether
Chapter6:MakingChoicesandDecisions
ConditionStatements
ControlFlowStatements
IfStatement
InlineIf
SwitchStatement
ForLoop
ForeachLoop
WhileLoop
Dowhile
JumpStatements
Break
Continue
ExceptionHandling
SpecificErrors
Chapter7:Object-OrientedProgrammingPart1
WhatisObject-OrientedProgramming?
Writingourownclass
Fields
Properties
Methods
Constructors
InstantiatinganObject
StaticKeyword
AdvancedMethodConcepts
UsingArraysandLists
Usingparamskeyword
PassingValueTypevsReferenceTypeParameters
Chapter8:Object-OrientedProgrammingPart2
Inheritance
WritingtheParentClass
WritingtheChildClass
TheMain()method
Polymorphism
GetType()andtypeof()
AbstractClassesandMethods
Interfaces
AccessModifiersRevisited
Chapter9:EnumandStruct
Enum
Struct
Chapter10:LINQ
Chapter11:FileHandling
ReadingaTextFile
WritingtoaTextFile
Project–ASimplePayrollSoftware
Overview
TheStaffClass
Fields
Properties
Constructor
Method
TheManager:StaffClass
Fields
Properties
Constructor
Method
TheAdmin:StaffClass
Fields
Property
Constructor
Method
TheFileReaderClass
ThePaySlipClass
Fields
Enum
Constructor
Methods
TheProgramClass
TheMain()Method
ThankYou
AppendixA–ProjectAnswer
Chapter1:IntroductiontoC#
WelcometoC#programmingandthankyousomuchforpickingupthis
book!
Whetheryouareaseasonedprogrammeroracompletenovice,thisbookis
writtentohelpyoulearnC#programmingfast.Topicsarecarefullyselected
togiveyouabroadexposuretoC#whilenotoverwhelmingyouwith
informationoverload.
Bytheendofthebook,youshouldhavenoproblemwritingyourownC#
programs.Infact,wewillbecodingasimplepayrollsoftwaretogetheraspart
oftheprojectattheendofthebook.Readytostart?
First,let’sanswerafewquestions:
WhatisC#?
C#,pronouncedasCSharp,isanobject-orientedprogramminglanguage
developedbyMicrosoftintheearly2000s,ledbyAndersHejlsberg.Itispart
ofthe.Netframeworkandisintendedtobeasimplegeneral-purpose
programminglanguagethatcanbeusedtodevelopdifferenttypesof
applications,includingconsole,windows,webandmobileapplications.
Likeallmodernprogramminglanguages,C#coderesemblestheEnglish
languagewhichcomputersareunabletounderstand.Therefore,C#codehas
tobeconvertedintomachinelanguageusingwhatisknownasacompiler
(refertofootnote).Thecompilerthatwe’llbeusinginthisbookisthefree
VisualStudioCommunity2015providedbyMicrosoft.
WhyLearnC#?
C#hassyntaxandfeaturesthatresembleotherprogramminglanguageslike
JavaandC++.Assuch,ifyouhaveanypriorprogrammingexperience,you
willfindlearningC#abreeze.Evenifyouaretotallynewtoprogramming,
C#isdesignedtobeeasytolearn(unlikeCorC++)andisagreatfirst
languagetolearn.
Inaddition,C#ispartofthe.Netframework.Thisframeworkincludesalarge
libraryofpre-writtencodethatprogrammerscanusewithouthavingtowrite
everythingfromscratch.Thisallowsprogrammerstorapidlydeveloptheir
applicationsinC#,makingC#theideallanguagetoworkwithifyouareona
tightschedule.
Lastly,C#isanobject-orientedprogramming(OOP)language.Objectorientedprogrammingisanapproachtoprogrammingthatbreaksa
programmingproblemintoobjectsthatinteractwitheachother.We’llbe
lookingatvariousobject-orientedprogrammingconceptsinthisbook.Once
youmasterC#,youwillbefamiliarwiththeseconcepts.Thiswillmakeit
easierforyoutomasterotherobject-orientedprogramminglanguagesin
future.
ReadytodipyourtoesintotheworldofC#programming?Let’sgetstarted.
Footnote:
TheconversionofaC#programintomachinelanguageisactuallyabitmorecomplicatedthanthis.
VisualStudioCommunitymerelyconvertsaC#programintoMIL,whichstandsforMicrosoft
IntermediateLanguage.ThisMILcodeisthenconvertedintomachinelanguagebyavirtualexecution
systemknownastheCommonLanguageRuntime.Formoreinformation,youcancheckout
Nonetheless,forourpurpose,wedonotneed
toknowtheseintricatedetailstodevelopourownC#programs.
Chapter2:GettingreadyforC#
InstallingVisualStudioCommunity
BeforewecanstartdevelopingapplicationsinC#,weneedtodownload
VisualStudioCommunity.AsmentionedinChapter1,VisualStudio
Community(VSC)isafreecomplierprovidedbyMicrosoft.
Infact,VSCismorethanjustacompiler.ItisanIntegratedDevelopment
Environment(IDE)thatincludesatexteditorforustowriteourcodeanda
debuggertohelpusidentifyprogrammingerrors.
TodownloadVSC,goto />
Clickonthe“DownloadCommunity2015”buttontodownloadthefile.Once
youhavedownloadedthefile,doubleclicktoinstallVSC.Afteryouinstall,
you’llbepromptedtorestartyourcomputer.
Onceyourestartyourcomputer,youarereadytostartcodingyourfirstC#
program.
YourFirstC#Program
Towriteourfirstprogram,let’screateafolderonourdesktopandnameit
“C#Projects”.WewillsaveallourC#projectstothisfolder.
Next,launchVSCandselectFile>New>Project….(Youmayhaveto
searchfor“VisualStudio2015”ifyoucannotfindVSC.)Thefirstprogram
thatwearegoingtowriteisaconsoleapplication.Consoleapplicationsrefer
toprogramsthathavenographicaluserinterface.
FromtheNewProjectdialogbox,select“VisualC#>Windows”(ontheleft)
andselect“ConsoleApplication”inthemainbox.
Namethisprogram“HelloWorld”andsaveitinthe“C#Projects”folder
createdearlier.Youcanusethe“Browse…”buttontobrowsetothecorrect
folder.Finally,clickOKtocreatetheproject.
YouwillbepresentedwithadefaulttemplatethatVSCcreatedforyou
automatically.
Replacethecodeinthetemplatewiththecodebelow.Notethatlinenumbers
areaddedforreferenceandarenotpartoftheactualcode.Youmaywantto
bookmarkthispageforeasyreferencelaterwhenwediscusstheprogram.
Duetothesmallscreensizesofmostmobiledevices,thecodemaylook
jumbledupifyouareviewingitonaKindle,tabletormobilephone.Ifyou
haveproblemsreadingthecode,youcantrychangingyourscreento
landscapemode.Alternatively,youcandownloadthesourcecodeforthis
sampleprogramandallothersampleprogramsinthisbookat
/>
1usingSystem;
2usingSystem.Collections.Generic;
3usingSystem.Linq;
4usingSystem.Text;
5usingSystem.Threading.Tasks;
6
7namespaceHelloWorld
8{
9
10//ASimpleProgramtodisplaythewordsHelloWorld
11
12classProgram
13{
14staticvoidMain(string[]args)
15{
16Console.WriteLine(“HelloWorld”);
17Console.Read();
18}
19}
20}
Istronglyencouragethatyoutypethecodeyourselftogetabetterfeelfor
howVSCworks.Asyoutype,youwillnoticethataboxappearsnearthe
cursorwithsomehelpmessagesoccasionally.ThatisknownasIntellisense.
Forinstance,whenyoutypeaperiod(.)aftertheword“Console”,adropdrop
listappearstoletyouknowwhatyoucantypeaftertheperiod.Thisisoneof
thefeaturesofVSCtohelpmakecodingeasierforprogrammers.
Afteryoufinishtyping,youcanexecutethisprogrambyclickingonthe
“Start”buttonatthetopmenu(refertoimagebelow).
Ifyourprogramfailstorun,VSCwillinformyouoftheerrorinthe“Output
Window”.Doubleclickingontheerrormovesthecursortowheretheerroris.
Doublecheckyourcodeagainstthecodeabovetorectifytheerrorandrun
theprogramagain.
Ifallgoeswellandyourprogramrunssuccessfully,ablackwindowwill
appearwiththewords“HelloWorld”inwhite.Thisblackwindowisknown
astheconsole.PressEntertoclosethewindow.
That’sit!Youhavesuccessfullycodedyourfirstprogram.Giveyourselfapat
ontheshoulders.
Ifyounavigatetoyour“C#Projects”foldernow,you’llfindafoldernamed
“HelloWorld”.Withinthefolder,you’llfindanother“HelloWorld”folderand
a“HelloWorld.sln”file.This.slnfileisthesolutionfile.Wheneveryouneed
toreopenaproject,thisisthefiletoopen.Ifthetexteditordoesnotdisplay
yourcodewhenyouopenthesolutionfile,simplydoubleclickonthe
“Program.cs”fileinthe“SolutionExplorer”ontheright(refertotheprevious
image)toopenit.
Theexecutablefile(.exe)ofyourcodecanbefoundintheHelloWorld>
HelloWorld>bin>Debugfolder.
BasicStructureofaC#Program
Now,letusdoaquickrun-throughofthebasicprogramthatyouhavejust
coded.
Directive
Fromline1to5,wehaveafewstatementsthatstartwiththewordusing.
Thesestatementsareknownasdirectives.Theytellthecompilerthatour
programusesacertainnamespace.
Forinstance,thefirstline
usingSystem;
tellsthecompilerthatourprogramusestheSystemnamespace.
Namespace
Anamespaceissimplyagroupingofrelatedcodeelements.Theseelements
includeclasses,interfaces,enumsandstructsetc(we’llcovereachofthese
elementsinsubsequentchapters).
C#comeswithalargeamountofpre-writtencodethatareorganisedinto
differentnamespaces.TheSystemnamespacecontainscodeformethodsthat
allowustointeractwithourusers.Weusetwoofthesemethodsinour
program-theWriteLine()andRead()methods.Theothernamespacesare
notneededinourprogram.However,sincethesenamespacesareincludedin
thedefaulttemplate,we’llleaveitinourcode.
Inadditiontothepre-writtennamespacesprovidedbyMicrosoft,wecanalso
declareourownnamespaces.
Oneadvantageofdeclaringnamespacesisthatitpreventsnamingconflicts.
Twoormorecodeelementscanhavethesamenameaslongastheybelongto
differentnamespaces.Forinstance,thecodebelowdefinestwonamespaces,
bothofwhichcontainaclassnamedMyClass.ThisisallowedinC#asthe
twoclassesbelongtodifferentnamespaces(FirstandSecond).
namespaceFirst
{
classMyClass
{
}
}
namespaceSecond
{
classMyClass
{
}
}
Inourexample,wedeclaredonenamespace-HelloWorld.
TheHelloWorldnamespacestartsonline7,withanopeningcurlybraceon
line8.Itendsonline20withaclosingcurlybrace.Curlybracesareused
extensivelyinC#toindicatethestartandendofacodeelement.Allopening
bracesinC#mustbeclosedwithacorrespondingclosingbrace.
WithintheHelloWorldnamespace,wehavetheProgramclasswhichstartson
line12andendsonline19.WithintheProgramclass,wehavetheMain()
methodthatstartsonline14andendsonline18.
TheMain()Method
TheMain()methodistheentrypointofallC#consoleapplications.
Wheneveraconsoleapplicationisstarted,theMain()methodisthefirst
methodtobecalled.
Inthisbook,wheneveryouareaskedtotryoutacertaincodesegment,you
shouldcreateanew“ConsoleApplication”andtypethegivencodesegment
intotheMain()method(betweenthecurlybraces).Youcanthenrunthe
programtotestthecode.
Noticethewords“string[]args”insidetheparenthesisofourMain()method?
ThismeanstheMain()methodcantakeinanarrayofstringsasinput.Donot
worryaboutthisforthemoment.We’llcoverthesetopicsinsubsequent
chapters.
Inourexample,theMain()methodcontainstwolinesofcode.Thefirstline
Console.WriteLine(“HelloWorld”);
displaystheline“HelloWorld”(withoutthequotes)onthescreen.
Thesecondline
Console.Read();
waitsforakeypressfromtheuserbeforeclosingthewindow.
Bothofthestatementsaboveendwithasemi-colon.Thisiscommonformost
statementsinC#.AftertheConsole.Read()statement,weendourcodewith
threeclosingbracestoclosetheearlieropeningbraces.
That’sit!There’sallthereistothissimpleprogram.
Comments
We’vecoveredquiteabitinthischapter.Youshouldnowhaveabasic
understandingofC#programmingandbereasonablycomfortablewithVSC.
Beforeweendthischapter,there’sonemorethingtolearn-comments.
Ifyoureferbacktoour“HelloWorld”exampleandlookatline10,you
shouldnoticethatthislinestartswithtwoforwardslashes(//).
//ASimpleProgramtodisplaythewordsHelloWorld
Thislineisactuallynotpartoftheprogram.Itisacommentthatwewriteto
makeourcodemorereadableforotherprogrammers.Commentsareignored
bythecompiler.
Toaddcommentstoourprogram,wetypetwoforwardslashes(//)infront
ofeachlineofcommentlikethis
//Thisisacomment
//Thisisanothercomment
//Thisisyetanothercomment
Alternatively,wecanalsouse/*…*/formultilinecommentslikethis
/*Thisisacomment
Thisisalsoacomment
Thisisyetanothercomment
*/
Commentscanalsobeplacedafterastatement,likethis:
Console.Read();//readsthenextcharacter
Chapter3:TheWorldofVariablesandOperators
NowthatyouarefamiliarwithVSCandhavewrittenyourfirstprogram,let’s
getdowntotherealstuff.Inthischapter,you’lllearnallaboutvariablesand
operators.Specifically,you’lllearnwhatvariablesareandhowtoname,
declareandinitializethem.You’llalsolearnaboutthecommonoperations
thatwecanperformonthem.
Whatarevariables?
Variablesarenamesgiventodatathatweneedtostoreandmanipulateinour
programs.Forinstance,supposeyourprogramneedstostoretheageofa
user.Todothat,wecannamethisdatauserAgeanddeclarethevariable
userAgeusingthefollowingstatement:
intuserAge;
Thedeclarationstatementfirststatesthedatatypeofthevariable,followedby
itsname.Thedatatypeofavariablereferstothetypeofdatathatthevariable
willstore(suchaswhetherit’sanumberorapieceoftext).Inourexample,
thedatatypeisint,whichreferstointegers.Thenameofourvariableis
userAge.
AfteryoudeclarethevariableuserAge,yourprogramwillallocateacertain
areaofyourcomputer’sstoragespacetostorethisdata.Youcanthenaccess
andmodifythisdatabyreferringtoitbyitsname,userAge.
DataTypesinC#
ThereareanumberofcommonlyuseddatatypesinC#.
int
intstandsforinteger(i.e.numberswithnodecimalorfractionalparts)and
holdsnumbersfrom-2,147,483,648to2,147,483,647.Examplesinclude15,
407,-908,6150etc.
byte
bytealsoreferstointegralnumbers,buthasanarrowerrangefrom0to255.
Mostofthetime,weuseintinsteadofbyteforintegralnumbers.However,
ifyouareprogrammingforamachinethathaslimitedmemoryspace,you
shouldusebyteifyouarecertainthevalueofthevariablewillnotexceedthe
0to255range.
Forinstance,ifyouneedtostoretheageofauser,youcanusethebytedata
typeasitisunlikelythattheuser’sagewilleverexceed255yearsold.
float
floatreferstofloatingpointnumbers,whicharenumberswithdecimal
placessuchas12.43,5.2and-9.12.
floatcanstorenumbersfrom-3.4x1038to+3.4x1038.Ituses8bytesof
storageandhasaprecisionofapproximately7digits.Thismeansthatifyou
usefloattostoreanumberlike1.23456789(10digits),thenumberwillbe
roundedoffto1.234568(7digits).
double
doubleisalsoafloatingpointnumber,butcanstoreamuchwiderrangeof
numbers.Itcanstorenumbersfrom(+/-)5.0x10-324to(+/-)1.7x10308and
hasaprecisionofabout15to16digits.
doubleisthedefaultfloatingpointdatatypeinC#.Inotherwords,ifyou
writeanumberlike2.34,C#treatsitasadoublebydefault.
decimal
decimalstoresadecimalnumberbuthasasmallerrangethanfloatand
double.However,ithasamuchgreaterprecisionofapproximately28-29
digits.
Ifyourprogramrequiresahighdegreeofprecisionwhenstoringnonintegral
numbers,youshoulduseadecimaldatatype.Anexampleiswhenyouare
writingafinancialapplicationwhereprecisionisveryimportant.
char
charstandsforcharacterandisusedtostoresingleUnicodecharacterssuch
as‘A’,‘%’,‘@’and‘p’etc.
bool
boolstandsforbooleanandcanonlyholdtwovalues:trueandfalse.Itis
commonlyusedincontrolflowstatements.We’llcovercontrolflow
statementsinChapter6.
NamingaVariable
AvariablenameinC#canonlycontainletters,numbersorunderscores(_).
However,thefirstcharactercannotbeanumber.Hence,youcannameyour
variablesuserName,user_nameoruserName2butnot2userName.
Inaddition,therearesomereservedwordsthatyoucannotuseasavariable
namebecausetheyalreadyhavepreassignedmeaningsinC#.Thesereserved
wordsincludewordslikeConsole,if,whileetc.We’lllearnabouteachof
theminsubsequentchapters.
Finally,variablenamesarecasesensitive.usernameisnotthesameas
userName.
TherearetwoconventionswhennamingavariableinC#.Wecaneitheruse
thecamelcasenotationoruseunderscores.Camelcasingisthepracticeof
writingcompoundwordswithmixedcasing,capitalisingthefirstletterof
eachwordexceptthefirstword(e.g.thisIsAVariableName).Thisisthe
conventionthatwe’llbeusingintherestofthebook.Alternatively,another
commonpracticeistouseunderscores(_)toseparatethewords.Ifyou
prefer,youcannameyourvariableslikethis:this_is_a_variable_name.
InitializingaVariable
Everytimeyoudeclareanewvariable,youneedtogiveitaninitialvalue.
Thisisknownasinitializingthevariable.Youcanchangethevalueofthe
variableinyourprogramlater.
Therearetwowaystoinitializeavariable.Youcaninitializeitatthepointof
declarationorinitializeitinaseparatestatement.
Theexamplesbelowshowhowyoucaninitializeavariableatthepointof
declaration:
Example1
Theseexamplesshowhowyoucaninitializebyteandintvariables.
byteuserAge=20;
intnumberOfEmployees=510;
Asbyteandintarefordatawithnodecimalplaces,youwillgetanerrorif
youwritesomethinglike
byteuserAge2=20.0;
20.0isnotthesameas20inC#.
Example2
Thenextexamplesshowhowyoucaninitializedouble,floatanddecimal
variableswithintegralvalues.Althoughthesedatatypesarefornumberswith
decimalparts,wecanalsousethemtostoreintegralvaluesasshownbelow.
doubleintNumberOfHours=5120;
floatintHourlyRate=60;
decimalintIncome=25399;
Example3
Theexamplesbelowshowhowyoucaninitializedouble,floatanddecimal
variableswithnonintegers.
doublenumberOfHours=5120.5;
floathourlyRate=60.5f;
decimalincome=25399.65m;
Asmentionedpreviously,thedefaultdatatypeforanumberwithdecimal
placesisdouble.
Hence,intheexamplesabove,whenyouinitializehourlyRate,youneedto
add‘f’asasuffixafter60.5toexplicitlytellthecompliertochange60.5toa
float.
Similarly,whenyouinitializeincome,youneedtoadd‘m’asasuffixto
change25399.65intoadecimaldatatype.
Example4
Achardatatypecanonlycontainasinglecharacter.Whenweinitializea