Sei sulla pagina 1di 42

C#

TheUltimateBeginner’sGuide!

AndrewJohansen

Copyright2016byAndrewJohansen-Allrightsreserved.

Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.The

publicationissoldwiththeideathatthepublisherisnotrequiredtorenderaccounting,officiallypermitted,orotherwise,

qualifiedservices.Ifadviceisnecessary,legalorprofessional,apracticedindividualintheprofessionshouldbeordered.

-FromaDeclarationofPrincipleswhichwasacceptedandapprovedequallybyaCommitteeoftheAmericanBar

AssociationandaCommitteeofPublishersandAssociations.

Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprinted

format.Recordingofthispublicationisstrictlyprohibitedandanystorageofthisdocumentisnotallowedunlesswith

writtenpermissionfromthepublisher.Allrightsreserved.

Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,intermsofinattentionor

otherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontainedwithinisthesolitaryandutter

responsibilityoftherecipientreader.Undernocircumstanceswillanylegalresponsibilityorblamebeheldagainstthe

publisherforanyreparation,damages,ormonetarylossduetotheinformationherein,eitherdirectlyorindirectly.

Respectiveauthorsownallcopyrightsnotheldbythepublisher.

Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationofthe

informationiswithoutcontractoranytypeofguaranteeassurance.

Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithoutpermissionor

backingbythetrademarkowner.Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandarethe

ownedbytheownersthemselves,notaffiliatedwiththisdocument.

TableofContents

Introduction

Chapter1:TheBasicsofC#

Chapter2:TheDataTypesandVariablesofC#

Chapter3:TheOperators

Chapter4:TheConditionalStatementsofC#

Chapter5:HowtoCreateandUseObjects

Chapter6:HowtoDefineClassesinC#

Conclusion

Introduction

Iwanttothankyouandcongratulateyouforpurchasingthisbook…

C#:TheUltimateBeginner’sGuide!

ThisbookwillexplainthefundamentalaspectsoftheC#language.Itwillteachyouthe

toolsandtechniquesthatyoucanuseincreatingyourownC#programs.Ifyouare

lookingforacomprehensiveguidefortheC#language,thisisthebookthatyouneed.

Byreadingthisbook,youwilllearnthebasicconceptsoftheC#languageandobject-

orientedprogramming.Youwillalsodiscoverthecomputerframeworkthatyouneedto

installbeforeusingthislanguage.Then,youwillknowhowtocreatevariables,methods,

constants,andclassesforyourprograms.

Thisbookcontainsscreenshots,actualcodes,andpracticalexamples.Thatmeansyouwill

beabletousethisbookevenifyouhaveneverprogrammedanythingbefore.Withthis

material,you’llmasterthebasicsofC#innotime.

Chapter1:TheBasicsofC#

Inthischapter,you’lllearnaboutthebasicsoftheC#programminglanguage.Byreading

thismaterial,you’llfamiliarizeyourselfwiththetools,tricks,andtechniquesthatyoucan

useincreatingC#programs.

TheThingsYouNeed

Yourcomputershouldhave“.NET,”theframeworkanddevelopmentkitforWindows computers. Modern Windows operating systems (i.e. Windows Vista, Windows 7,

Windows8,andWindows10)have.NETasapreinstalledframework.Thus,ifyouare

usingWindows7,youdon’thavetoinstallanyadditionalsoftware.

Ifyourcomputerdoesn’thave.NET,youcandownloaditforfree.Simplyvisittheofficial

websiteofMicrosoft(i.e.www.microsoft.com)andsearchforthesaidframework.

ImportantNote:IfyouareusingaMac,UNIX,orLinuxcomputer,youneedtogetMono

Projectinstead.Thisdevelopmentkitwillprovideyouwitheverythingyouneedinorder

tocreateC#programs(e.g.compiler,classes,library,.NETruntime,etc.).Youmayvisit

thewww.mono-project.comwebsitetogettheframeworkorgetmoreinformationabout

it.

C#–APowerfulLanguage

According to computer experts, C# is the best programming language for Windows computers.Itisperfectlycompatiblewiththe.NETframeworkanditallowsWindows userstowriteprogramswithoutdownloadinganysoftware.Thislanguageofferspower, flexibility and simplicity. If you’re an inexperienced programmer, this is the ideal languageforyou.

SimilartotheJavalanguage,C#doesn’tsupportcodepointersor“multipleinheritance.”

Instead,itoffersmemorycollectionandtypechecking.Additionally,C#hasthemost

powerfulfeaturesofC++(e.g.enumerations,overloading,preprocessordirectives,etc.).

CreatingYourFirstC#Program

Inthispartofthebook,you’llwriteabasiccomputerprogram.Despiteitssimplicity,this

exercisewillteachyouhowtocreate,compile,andrunaC#program.Followthesteps

givenbelow:

Launchyourfavoritetexteditor.Ifyou’reusingaWindowscomputer,youmay

useNotepad.IfyourcomputerrunsonLinux,however,youmaylaunch“vi”or

1.
1.

“vim.”

2.
2.

Typethiscode:

classFirstProgram

staticvoidMain()

{
{

Console.WriteLine(“TheC#languageisawesome.”);

Savethefileas“FirstProgram.cs”.Basically,youshouldusethe“.cs”extension

whenwritingsourcecodesusingtheC#language.

4.
4.

Accessyourcommandpromptandtype:

cscFirstProgram.cs

After issuing that command, the C# compiler installed in your computer will processthe.csfile.Thiswillcreatea.exefileinthesamelocationasthesource code.Forinstance,ifyousavedthe.csfileinyourdesktop,you’llseeaprogram named“FirstProgram.exe”inthatdirectory.

ImportantNote:Thecommandpromptwilldisplayanerrormessageifthere’sa

problemwiththesourcecode.

5.
5.

Runtheapplicationbyentering“FirstProgram.exe”inyourcommandprompt.

6.
6.

Ifyoudideverythingcorrectly,yourcommandpromptshoulddisplaythe

followingmessage:

“TheC#Languageisawesome.”

AnalyzingtheProgram

NowthatyouhavecreatedaC#program,let’sperformadetailedanalysistohelpyou

understandhowthislanguageworks.

Thefirstline–Thislineconsistsofonekeyword(i.e.class)andoneidentifier(i.e. FirstProgram).Basically,akeywordisawordthathasspecialfunctionsinthe programming language. This keyword, in particular, creates a class for your program.Aclassisacombinationoffunctionsandinformationthatyoucanusein yourprogram.You’llknowmoreaboutC#classeslaterinthisbook.

Theidentifier,ontheotherhand,helpsyouidentifyclasses,variables,andmethods that you want to include in your program. In this example, the identifier “FirstProgram”servesasthenameoftheclassyouwanttocreate.

Thethirdline–Thislinedefinesamethod(i.e.Main())foryourprogram.InC#,

Main()actsasthestartingpointofanycomputerapplication.Programsstarttheir

executionintheMain()method(regardlessoftheirplacementinthecode).TwoC#

keywordsprecedethemethod,namely,“static”and“void.”Here,“static”informs

thelanguagecompilerthatthemethodwillnotcreateanyobjectwithintheclass.

Thekeywordcalled“void,”ontheotherhand,tellsthecompilerthatMain()won’t

returnanyvalue.

Thefifthline–Thisisthefinalpartofthecode.Itisthelinethatdisplaysthe

messageonyourcommandprompt.Here,youusedamethodcalledWriteLine()to

capturea“string”(i.e.acombinationofmultiplecharacters)andprintitonthe

screen.

Justlikeanyobject-orientedlanguage,C#accessesthemethodsandvariablesofa

classusingthedotoperator(i.e“.”).Additionally,C#requiresprogrammerstouse

bracesinidentifyingcodeblocks.Lastly,programmersneedtoendC#usinga

semicolon(similartoCandJava).

C#Comments

Thisprogramminglanguageallowsyoutowritecommentsinyourcodes.Acommentisa

line(oracollectionoflines)thatgivesmoreinformationregardingthecodeblockto

whichitisadded.Thelanguagecompilerignorestheselines,whichmeanscomments

won’thaveanyeffectonthebehaviororfunctionalityofyourprogram.

C#supportstwotypesofcomments,namely:

Single-LineComments–Thiskindofcommentbeginswithtwoforwardslashes.

Asitsnameimplies,asingle-linecommentshouldbelimitedtoasingleline.You’ll

getanerrormessageifyou’llforgetaboutthissimplerule.Thecodesnippetgiven

belowwillshowyouhowtocreateasingle-linecomment:

staticvoidMain()

{//Ihaveapet.}

Multi-LineComments–Insomecases,single-linecommentsarenotenoughto

explainthefunctionsyou’reworkingon.Becauseofthis,C#allowsyoutowrite

multi-linecomments.Amulti-linecommentisacommentthatspansseverallines.

Itbeginswith“/*”andendswith“*/”.Here’sanexample:

staticvoidMain()

{
{

/*TheC#compiler

will ignore

thiscodeblock.*/

}
}

TheThingsYouShouldKeepInMind

TheThingsYouShouldKeepInMind AC#programexistsinsideaclass.

AC#programexistsinsideaclass.

EachC#programstartsitsexecutioninthemethodcalledMain().

EachC#programstartsitsexecutioninthemethodcalledMain(). This programming language is case-sensitive. Thus, class and

This programming language is case-sensitive. Thus, class and CLASS are two differentthings.

Thecompilerignores“whitespaces”(i.e.newlines,spaces,andtabcharacters).You

canusewhitespacesfreelywhilewritingyourcodes.Checkthefollowingsample:

static

void

Main()

{WriteLine(“Thisisjustasample.”);

}
}

C#allowsyoutouseanynameforyourprograms.Additionally,theclassidentifier

andtheprogram’snamedon’thavetobeidentical.

YourprogramcancontainseveralMain()methods.

Youshouldusecurlybraces(i.e.{})todefinetheboundariesofaclassormethod.

TheC#languagesupportstwotypesofcomments:single-lineandmulti-line.

YoucanaddastringandanargumenttoyourMain()method.

Chapter2:TheDataTypesandVariablesofC#

ThischapterfocusesonthedatatypesandvariablesavailableinC#.Studythismaterial

carefullyasitcanhelpyoubecomeaskilledcomputerprogrammer.

DataTypes

C#expertsdividedatatypesintotwocategories:valuetypesandreferencetypes.When

workingwithavaluetype,youshouldpassthedatatothemethodyou’reusing.Reference

types,ontheotherhand,simplyaddareferenceintothemethod(i.e.Thevalueisstored

elsewhere.).

Herearethedatatypesthatyou’llencounterwhileusingC#:

ByteHerearethedatatypesthatyou’llencounterwhileusingC#: Short Sbyte Ushort Int Uint Float Long Double Ulong

ShortHerearethedatatypesthatyou’llencounterwhileusingC#: Byte Sbyte Ushort Int Uint Float Long Double Ulong

SbyteByte Short Ushort Int Uint Float Long Double Ulong

UshortByte Short Sbyte Int Uint Float Long Double Ulong

IntByte Short Sbyte Ushort Uint Float Long Double Ulong

UintByte Short Sbyte Ushort Int Float Long Double Ulong

FloatByte Short Sbyte Ushort Int Uint Long Double Ulong

LongByte Short Sbyte Ushort Int Uint Float Double Ulong

DoubleByte Short Sbyte Ushort Int Uint Float Long Ulong

UlongByte Short Sbyte Ushort Int Uint Float Long Double

Bool–Whenusingthistype,thevaluesthatyoucanstorearelimitedtotwo.These

valuesare“true”and“false”.Thisdatatypeisidealforlogicalexpressionsand

conditionalstatements.

Char–Thisdatatypecanholdasinglecharacter.Whilewritingacharvalue,you

needtoencloseitinsinglequotes(e.g.‘t’,‘1’,‘g’,etc.).

DecimalVariables

Variables

Duringexecution,acomputerprogramstoresdatatemporarily.Programmersusetheterm

“variables”whenreferringtothememorylocationthatholdsthestoreddata.Thus,a

variablehasacorrespondingvalueanddatatype.

IntheC#language,youcancreate(i.e.declare)variablesusingthefollowingsyntax:

<data_type><name_of_variable>;

Forinstance:

Thelinegivenabovewillreserveacertainpartofcomputermemorytoholdacharvalue. Then,theprogrammercanaccessthatvariableusingitsidentifier(i.e.x).C#allowsyouto initializevariablesduringthedeclaration.Theterm“initialization”referstotheprocessof assigning an initial value to a variable during its creation. You just have to use the assignmentoperator(i.e.“=”)andindicatethevalueyouwanttoassign.Herearesome examples:

charx;
charx;

charsample=‘5’;

boolisItDelicious=false;

intyear=2016;

Additionally,youcandeclaremultiplevariablesinasinglestatementiftheybelongtothe

samedatatype.Youjusthavetoseparatetheentriesusingcommas.Checktheexamples

below:

inttest=1,example=100,extra=1000;

charant=‘a’,bull=‘b’,cat=‘c’;

Justlikeanyprogramminglanguage,C#requiresyoutodeclarevariablesbeforeaccessing

them.Thislanguagealsoimplementsarulecalled“definiteassignment.”Accordingto

thisrule,youneedtoinitializealocalvariable(i.e.avariablewritteninsideamethod)

beforeusingit.Thatmeansyouhavetoassignaninitialvaluetoalocalvariableduringits

declaration.

ImportantNote:Variablesarenamedassuchbecausethevaluestheystorechangeeach

timetheprogramruns.Basically,thevaluethattheystoredependsontheuser’sinputs.

Constants

Aconstantisatypeofvariablethatpreventsprogramsfromchangingitsinitialvalue.

Thus,thevalueofaconstantwillstaythesameregardlessoftheuser’sinputs.Youneed

touse“const”(i.e.anotherC#keyword)whendeclaringaconstant.Here’sanexample:

constcharLETTER=x;

Keepinmindthatprogramscannotalteraconstant’svalue.Thatmeansyouneedtoassign

aninitialvaluetoitduringthevariabledeclaration.Thesamplegivenbelowwillgiveyou

anerrormessageduringcompilation:

constboolANSWER;

ImportantNote:Mostprogrammersuseuppercaseletterswhendeclaringaconstant.

CreatinganIdentifier

MicrosoftrecommendstheCamelnotationwhennamingvariablesandthePascalnotation

whennamingmethods.IntheCamelnotation,thefirstletterofthewordshouldbein

lowercase.Ifitisacompoundword,thefirstletterofthesecondwordshouldbeginwith

anuppercaseletter.Herearesomeexamples:

payment

totalPayment

mathematics

mathSkills

 

The Pascal notation, on the other hand, requires you to start the first word with an uppercaseletter.Theinitialletteroftheadditionalwordsshouldbeinuppercasetoo. Checkthesamplesgivenbelow:

WriteLine()

ReadLine()

Start()

Main()

 

Youcanalsousenumbersandtheunderscorecharacterincreatingidentifiers.However,

identifierscannotstartwithanumber.Forexample,sixDogsisvalidwhile6Dogsisnot.

ImportantNote:Thesenotationsaren’tmandatory.However,youareadvisedtousethem

whilewritingC#statements.Thisway,youcanachievecleanlinessandreadabilityinyour

sourcecodes.

Chapter3:TheOperators

Operators help your programs in handling values and performing tasks. Without any operator,computerprogramswillbeutterlyuseless.Thatmeansyouhavetostudyhow operatorsworkandhowyoucanaddthemintoyourcodes.

InC#,justlikeinanyprogramminglanguage,operatorsbelongtodifferentcategories.

Let’sdiscusseachcategoryindetail:

TheArithmeticOperators

Theseoperatorsallowcomputerprogramstoperformarithmeticprocedures.Herearethe

arithmeticoperatorsavailableinC#:

ImportantNote:Let’sassumethatx=10;andy=20.

“+”–Thisisknownasthe“additionoperator.”Useittoaddthevalueoftwo

operands.Forexample,x+y=30.

“-”–Programmersrefertothissymbolasthe“subtractionoperator.”Itallowsyou tosubtractthevalueoftheright-handoperandfromthatoftheleft-handoperand.

Forinstance,y–x=10.

“*”–Withthisoperator,youcanmultiplythevalueoftwooperands.Forexample,

x*y=200.

“/”–Thisoperatorallowsyoutodividethevalueoftheleft-handoperandbythat

oftheright-handoperand.Here’sanexample:y/x=2.

“%”–C#userscallthisthe“modulo”or“remainder”operator.Itdividesthevalue of the left-hand operand by that of the right-hand operand and returns the

remainder.Forexample:10%3=1.

“++”–Thisisknownasthe“increment”operator.Itincreasesthevalueofan

operandbyone.Thus,++x=11.

“—”–Programmersrefertothisas“decrement”operator.Itdecreasesthevalueof

anoperandbyone.Forexample,==y=19.

ImportantNote:Theincrementanddecrementoperatorsareunary.Thatmeanstheycan

beusedonasingleoperand.Additionally,youcanaddtheseoperatorseitherbeforeor

aftertheoperandyou’reworkingon.Intheexamplesgivenabove,x++andy—willgive

thesameresults.

Thecodegivenbelowshowsyouhowtoaddarithmeticoperatorsinyourcodes.

classExample

{
{

//Thisbasicprogramwillshowyouhowarithmeticoperatorswork.

staticvoidMain()

{
{

intf=3,g=4;

//Thislinedeclarestwovariables,fandg.

sampleSum=f+g;

//Thiswillgiveyou7.

sampleDifference=g–f;

//Thiswillgiveyou1.

sampleProduct=f*g;

//Thiswillgiveyou12.

sampleQuotient=g/f;

//Thiswillgiveyou1.3

sampleModulo=g%f;

//Thiswillgiveyou1.

f++;

//Thiswillgiveyou4.

—g;

//Thiswillgiveyou3.

} }
}
}

TheAssignmentOperators

Asitsnameimplies,anassignmentoperatorletsyouassignavaluetoavariable.Hereare

theassignmentoperatorsthatyoucanuseinC#:

“=”–Thisoperatorallowsyoutoperforma“simpleassignment”operation.Itwilljust

assignthespecifiedvaluetothevariableyou’reworkingon.Forexample,theexpression

simply assigns 100 to the int variable named “sample”. It doesn’t

performextraprocessesonthevariableorthevalueinvolved.

“+=”–Thisisthe“additiveassignmentoperator.”Itaddsupthevaluesoftwooperands

andassignsthesumtotheleft-handoperand.

“-=” – Programmers refer to this symbol as the “subtractive assignment operator.” It subtracts the value of the right-hand operand from that of the left-hand operand and assignsthedifferencetotheleft-handoperand.

“*=”–Thisoperator,knownasthe“multiplicativeassignmentoperator,”multipliesthe

valuesofbothoperandsandassignstheproducttotheleft-handoperand.

“/=” – This is the division assignment operator. It divides the value of the left-hand operand by that of the right-hand operand and assigns the quotient to the left-hand operand.

“%=”–Programmersusetheterm“moduloassignmentoperator”whenreferringtothis

symbol.Youcanusethisoperatortoperformamodulooperationontwovariablesand

assigntheresulttotheleft-handvariable.

intsample=100

ImportantNote:Whenusinganyassignmentoperator,makesurethatbothoftheoperands

belongtothesamedatatype.Iftheoperandsareincompatible,yourprogramwilldisplay

unexpectedand/orundesirablebehaviorsduringruntime.

TheRelationalOperators

Theseoperatorsallowyoutocomparethevaluesoftwooperands.Becauseofthat,they

areidealforconditionalstatements.Herearetherelationaloperatorsthatyou’llencounter

inC#:

ImportantNote:Let’sassumethatd=100ande=200.

“==”–Thisoperatorallowsyoutochecktheequalityoftwovalues.Ifthevalues

areequal,theoperandwillgiveyoutrue;otherwise,itwillgiveyoufalse.For

example,“d==e”evaluatestofalse.

“!=”–Withthisoperator,youcantesttheinequalityoftwovalues.Ifthevaluesare

notequal,itwillgiveyoutrue.Forinstance,“e!=d”resultsintrue.

“>”–Youcanusethisoperatortocheckwhetherthevalueoftheleft-handoperand

isgreaterthanthatoftheright-handoperand.Ifitis,theoperatorwillgiveyoutrue.

Forinstance,“d>e”evaluatestofalse.

“<”–Programmersrefertothisasthe“lessthan”operator.Itallowsyoutocheck whether the value of the left-hand operand is less than that of the right-hand operand.Ifyes,youwillgettrue.Forexample,“d<e”willgiveyoutrue.

“>=”–Thisoperatorwillgiveyoutrueifthevalueoftheleft-handoperandis

greaterthanorequaltothatoftheright-handoperand.Otherwise,itwillgiveyou

false.Forinstance,“e>=d”evaluatestotrue.

“<=”–Withthisoperator,you’llgettrueiftheleft-handoperand’svalueisless

thanorequaltothatoftheright-handoperand.Forexample,“d<=e”willgiveyou

true.

ImportantNote:Whenusingarelationaloperator,theresultthatyouwillgetisalwaysa Booleanvalue(i.e.trueorfalse).Additionally,makesurethatyouareusingtwoequal signs while using the equality operator. Keep in mind that “=” assigns a value to a variable.Thus,ifyou’llgetconfusedbetweentheassignmentoperator(i.e.“=”)andthe equalityoperator(i.e.“==”),yourprogramwillproduceerrorsorundesirableresults.

TheLogicalOperators

Alogical(alsocalledBoolean)operatoracceptstwoBooleanvaluestoproduceanew

Booleanvalue.C#supportsfourlogicaloperators.

ImportantNote:Let’sassumethatc=true,d=true,andc=false.

“&&”–ThisoperatoriscalledLogicalAND.Itwillonlygiveyoutrueifboth

operandsaretrue.Forexample,“d&&c”evaluatestofalse.

“||”–ProgrammersrefertothisoperatorasLogicalOR.Thisoperatorwillgiveyou

trueifatleastoneoftheoperandsistrue.Thus,c||eresultstotrue.

“^”–Thisoperator,knownasLogicalExclusiveOR,willgiveyoutrueifoneof

theoperandsistrue.Ifbothoperandsaretrueorfalse,thisoperatorwillgiveyou

false.

“!”–Withthisoperator,youcanreversethevalueofaBooleanvariable.For

example,“!d”evaluatestofalse.

Someprogrammersreferto“&&”and“||”asshort-circuitoperators.That’sbecausethey

cangiveanaccurateresultevenwithoutcheckingtheentireBooleanexpression.For

example,since&&requirestwo“trues”,itwillgiveyoufalseifthefirstoperandis

alreadyfalse.Itwon’tcheckthesecondoperandanymore.TheLogicalORoperator,on

theotherhand,willgiveyoutrueifthefirstoperandisalreadytrue.Itwillterminatethe

processsinceitsconditionhasalreadybeenmet.

TheBitwiseOperators

Abitwiseoperatorworkslikealogicaloperator.Theonlydifferenceisthatabitwise operatortakesbinaryvaluestoproduceaBooleanresult.Sinceabitwiseoperatorworks onbinarydata(i.e.valuesthatarecomposedofonesandzeros),theyshowtheresultby

placingeither“1”or“0”intheiroutput.

TheC#languagesupportsthefollowingbitwiseoperators:

ImportantNote:Let’sassumethatg=1,h=1,i=0,andj=0.

“&”–ThisoperatorisknownasBitwiseAND.Itassigns“1”tothepositions

wherebothoperandshave“1”.Forexample,“g&h”willgiveyou“1”.

“|” – Programmers refer to this operator as “Bitwise OR.” It assigns 1 to the

positionswhereatleastoneoperandhas1.Forinstance,“h|i”willgiveyou1.

“^”–TheExclusiveORoperatoralsoworksforbinarydata.JustlikeinLogical

values,thisoperatorwillgiveyou1inpositionswhereonlyoneoftheoperands

has1.Forexample,“g^j”willgiveyou1.

“~”–Thisiscalledthe“BitwiseNegation”operator.Itreversesthevalueofa

binarydata.Forexample,“~i”evaluatesto1.

Chapter4:TheConditionalStatementsofC#

Conditionalstatementshelpprogrammersincreatingpowerfulandflexibleapplications.

Infact,conditiontestinghasalwaysbeentreatedasanimportantpartofwritingcomputer

programs.IfyouwanttobeaneffectiveC#programmer,youneedtomasterconditional

statements.

If

Programmers consider this as the basic conditional statement of C#. It allows your programstobehaveaccordingtotheuser’sinputs.Thesyntaxofan“if”statementis:

if(TheBooleanexpression)

{
{

Thestatement/syouwanttorun

}
}

Thissyntaxconsistsofthreeparts,namely:

} Thissyntaxconsistsofthreeparts,namely:

The“if”keyword–Thispartinformsthelanguagecompilerthatyouarecreating

an“if”statement.

The Boolean expression – This portion of the syntax determines whether the programwillrunthe“body”ornot.InC#,youcannotuse“int”and“char”values forthisexpression.

Thestatement/syouwanttorun–Thispart,alsoknownasthe“body,”iscomposed ofoneormoreC#statements.Theprogramwillexecutethesestatementsifthe result of the Boolean expression is “true.” If the result is false, however, the program will ignore the “body” and pass the control to the succeeding C# statements.

Thefollowingexamplewillshowyouhow“if”statementswork:

if(x>0)

{
{

Console.Write(“Thevalueispositive.”);

}
}

Inthisexample,theprogramwillprint“Thevalueispositive.”onthescreenONLYIFx

isgreaterthanzero.Ifthisexpressionevaluatestofalse,theprogramwillignorethe

Console.Writestatementcompletely.

IfElse

TheC#languagesupports“else”,aclausethatyoucanaddtoyour“if”statements.The

syntaxofan“ifelse”statementis:

if(TheBooleanexpression)

{Thestatement/syouwanttoruniftheresultistrue;

} else
}
else

{Thestatement/syouwanttoruniftheresultisfalse;

}

Thiskindofconditionalstatementhasfiveparts,namely:

The“if”keyword–Withthiskeyword,youareinformingtheC#compilerthatyou

arecreatingaconditionalstatement.

TheBooleanexpression–ThisC#expressionshouldresultinaBooleanvalue.If this expression evaluates to true, the program will run the first body of the conditionalstatement.

Thefirst“body”–Thisisastatementoragroupofstatementsthatwillrunifthe

Booleanexpressionresultsin“true”.

The“else”keyword–ThiskeywordinformstheC#compilerabouttheexistenceof

an“else”clause.ThispartofthestatementrunsiftheBooleanexpressionisfalse.

Thesecond“body”–Similartothefirst“body,”thispartofthecodecanbea

singlestatementorasetofstatements.

Asyoucansee,an“ifelse”statementismuchmorepowerfulthanan“if”statementasthe

formergivesyoumorecontroloveryourprogram.

Thecodesnippetgivenbelowwillshowyouhow“ifelse”statementswork:

if(x>0)

{
{

Console.Write(“Thevalueispositive.”);

} else
}
else

{

Console.Write(“Thevalueislessthanorequaltozero.”)

}

Here,thebodyofthe“else”clausewillonlyruniftheBooleanexpressionevaluatesto

false.Thus,theprogramwillignorethispartiftheevaluationistrue.

NestedConditionalStatements

C#allowsyoutowritean“if”statementwithinanother“if”statement.Thisprocess,

whichiscalled“nesting,”canhelpyoucreatecomplexprogramsthatrelyonchained

conditions.Ifyou’llusethisfunctionalitywith“if-else”statements,each“else”clause

pointstothe“if”clausethatcomesbeforeit.Keepthisruleinmind—you’llencounter

compile-timeandsyntaxerrorsifyou’llmakeamistakeinwritingnestedconditional

statements.

AccordingtoC#experts,yournestedstatementsshouldbelimitedtothreelevels.Ifyou’ll

exceedthethree-levellimit,yourcodeswillbecomplexandconfusing.

Thecodegivenbelowwillshowyouhowtonestaconditionalstatement:

doubler=50;

doubles=60;

if(r==s)

{
{

System.Console.WriteLine(“Thesenumbersareequal.”);

} else {
}
else
{

if(r>s)

{
{
System.Console.WriteLine(“Thevalueofthefirstvariableisgreaterthanthatofthe secondone.”);
System.Console.WriteLine(“Thevalueofthefirstvariableisgreaterthanthatofthe

System.Console.WriteLine(“Thevalueofthefirstvariableisgreaterthanthatofthe

System.Console.WriteLine(“Thevalueofthefirstvariableisgreaterthanthatofthe secondone.”);
secondone.”);

secondone.”);

} else {
}
else
{
System.Console.WriteLine(Thevalueofthesecondvariableisgreaterthanthatofthe firstone.”);
System.Console.WriteLine(Thevalueofthesecondvariableisgreaterthanthatofthe

System.Console.WriteLine(Thevalueofthesecondvariableisgreaterthanthatofthe

System.Console.WriteLine(Thevalueofthesecondvariableisgreaterthanthatofthe firstone.”);
firstone.”);

firstone.”);

} }
}
}

Switch-Case

Switch-casestatementsexecutecodesaccordingtotheresultofanexpression.Often,C#

programmersuseintegervalueswhenworkingwiththisconditionalstatement.Tocreatea

switch-casestatement,youshouldusethefollowingsyntax:

switch(value_selector)

{ caseinteger1; thestatementsyouwanttoexecute; break; caseinteger2; thestatementsyouwanttoexecute; break; //…
{
caseinteger1;
thestatementsyouwanttoexecute;
break;
caseinteger2;
thestatementsyouwanttoexecute;
break;
//…
default:
thestatementsyouwanttoexecute;
break;
}

Thissyntaxconsistsofthefollowingparts:

break; } Thissyntaxconsistsofthefollowingparts:

The“switch”keyword–Thiskeywordinformsthecompilerthattheprogramhasa

switch-casestatement.

Thevalueselector–Thisisanexpressionthatgeneratesavalue.InC#,thevalue

shouldbecompatiblewiththecomparisonoperators.Yourprogramwillcompare

thisvalueagainstthecaseslistedinsidetheswitch-casestatement.

The “case” – Basically, a case is a label used by the program in performing comparisons.Ifacasematchesthevaluefromtheselector,itsstatementswillrun. Theprogramwillcheckeachcaseuntilamatchisfound.

Theexecutablestatements–Thesearethestatementsthatyouwanttorunbasedon

theappropriatecase.Itcanbeasinglestatementoragroupofstatements.

Thebreakkeyword–Thiskeywordterminatesthebodyofaswitchstructure.As

youcansee,youneedtoplacethiskeywordoneverycasestatementthatyou’ll

create.

Thedefaultclause–Considerthispartasa“catch-all”mechanism.Itwillrunifthe

valuegeneratedbytheselectordoesn’tmatchanyofthelistedcaselabels.Withthis

clause,youcanmakesurethatyourprogramwillhaveananswerregardlessofthe

user’sinputs.

Chapter5:HowtoCreateandUseObjects

Thischapterwillfocusontwoprogrammingconcepts:objectsandclasses.Here,youwill

learnhowtoaccesstheclassespresentinthe.NETprogrammingframework.Readthis

materialcarefullyasitcontainsvaluableinformationthatcanhelpyoumasterC#quickly

andeasily.

ObjectsandClasses

Programminghasexperiencedhugegrowthduringthepastfewyears.Thisgrowthhasan incredibleeffectonhowmodernprogrammerscreatecomputerapplications.Accordingto C# experts, OOP (Object-Oriented Programming) is one of the biggest ideas to be developedintheworldofIT.Inthispartofthebook,you’lllearnhowOOPworksand howitcanhelpyouincreatingawesomeprograms.

Object-OrientedProgramming

Basically,object-orientedprogrammingisastyleofprogrammingthatreliesonobjects. OOPgivesyouaprogrammingmodelthatisbasedonhowthingsworkintherealworld. With this approach, you’ll be able to solve programming problems using logic and intuition.

Objects

Programmersusedigital“objects”torepresentabstractideasorphysicalobjects(e.g.cars, books, pens, etc.). While using OOP, you need to remember that objects have two characteristics,namely:

State – This characteristic defines an object. The definition can be specific or general.

an object. The definition can be specific or general.

Behavior–Thischaracteristicdeclarestheactionsthattheobjectcando.

Tohelpyouunderstandthesecharacteristics,let’sapplythemonanactualobject—a

motorcycle.Thestateofthemotorcyclewilldefineitsmake,colorandsize.Itsbehavior,

however,is“moving.”

In object-oriented programming, you’ll combine information and the techniques for processingthemintoone.Aprogrammingobjectcorrespondstoanactualoneandholds actionsandinformation.

Classes

InC#,classesdefinethecharacteristicsofanobject.Theyprovideyouwithastructurefor objectutilizationoramodelfordefininganobject’snature.Accordingtoprogramming experts, classes serve as the foundation of OOP and are closely linked to objects. Additionally,eachobjectrepresentsoneparticularclass.

Let’sassumethatweareworkingwithaclassnamed“Vehicle”andanobjectnamed “Motorcycle”. Here, “Motorcycle” is just a single instance of the “Vehicle” class. “Vehicle”definesthestateandbehaviorofallvehicleswhileMotorcycleisavehicle.

Classesaddmodularityandsimplicitytocomputerprogramming.Theinformationthey

containshouldbemeaningfultoeveryone,eventopeoplewhoarenotprogrammers.For

example,theclassnamed“Vehicle”cannotcontainHTTPasoneofitscharacteristics

sincethelattercannotbepossiblylinkedtotheformer.

BehaviorandAttributes

Classesdefineanobject’sbehavior(theactionsthattheobjectcanperform)andattributes

(alsoknownascharacteristics).Attributesappearasvariablesinthebodyoftheclass.The

behavior,ontheotherhand,isdefinedbythemethodswithinthatclass.

IfyouwillapplytheseontheVehicleclass,youwillget“make”and“size”asattributes.

Then,themethodsthatyouwilluseare“move()”and“stop()”.

HowtoUseClassesinYourPrograms

InC#,youshoulddefineeachofyourclassesusingthe“class”keyword.Aftertyping

“class”,youneedtoindicatetheidentifieryouwanttouseaswellasthemethodsand

variablesyouwanttoplaceinsidethenewclass.AC#classcanhavethefollowingparts:

Fields–Thesearevariablesthatbelongtoaparticulardatatype.

Methods–Youcanusemethodstomanipulatedata.

Properties – In C#, “properties” enhance the functionality of the “fields.” A propertyprovidesextrainformationmanagementabilitiestoafield.You’lllearn aboutthistopicinalaterchapter.

Thefollowingsamplecontainsallofthepartsdiscussedabove.Thenameofthisclassis

“Book”andithastwoproperties:typeandsize.Here,youwillknowhowtodefinefields,

methods,andproperties.

methods,andproperties. publicclassBook { privatestringbookType; privatestringsize;

publicclassBook

{
{

privatestringbookType;

privatestringsize;

publicstringBookType

{ get {
{
get
{

returnthis.bookType;

} set {
}
set
{

this.bookType=value;

publicstringSize

{
{

get

{

returnthis.size;

}

set

{

this.size=value;

}

 

}

publicBook()

{

 

this.bookType=“Dictionary”;

this.size=“large”;

}

publicBook(stringbookType,stringsize)

{

this.bookType=bookType;

this.size=size;

}

publicvoidSample()

{

Console.WriteLine(“Isthisa{0},bookType);

In this example, the class named Book defines two properties, namely, Size and BookType. These properties hide their values inside the fields named “size” and

“bookType”.Additionally,thecodesnippetdeclarestwoconstructorsforgeneratingan

instanceoftheBookclass.Lastly,thiscodecreatesamethodcalled“Sample()”.

Aftercreatingaclass,youwillbeabletouseitforyourC#programs.Thecodegiven

belowshowsyouhowtouseaclasswhenwritingcodes:

staticvoidMain()

{ BookfirstBook=newBook(); firstBook.BookType=“Dictionary”; firstBook.Sample();
{
BookfirstBook=newBook();
firstBook.BookType=“Dictionary”;
firstBook.Sample();
CatsecondBook=newBook(“Bible”,“small”);
secondBook.Sample();
Console.WriteLine(“Thatisa{1}{0}.”,secondBook.BookType,secondBook.Size;
}

TheSystemClasses

TheC#languagehasbuilt-instandardlibraries.Theselibrariescontaindefaultclasses

suchasString,Math,andConsole.AsaC#user,youneedtokeepinmindthatstandard

librariesarecompatiblewithany.NETapplication.

The.NETframeworkhasapreinstalledlibrarythatcontainsnumerousclasses.These

classeshelpyouaccomplishbasicprogrammingtaskssuchasnetworking,execution,and

textprocessing.

You should know that classes hide their logical implementation inside them. As a programmer,youshouldfocusonwhatclassescando,notonhowtheydoit.Forthat reason,mostofthebuilt-inclassesofC#arenotviewable.This“principleofabstraction” isafundamentalpartofobject-orientedprogramming.

ImportantNote:You’lllearnmoreaboutthebuilt-inclassesinalaterchapter.Fornow,

youwilllearnhowtocreateyourownobjects.

HowtoCreateandUseanObject

Inthispartofthebook,you’lllearnhowtocreateanduseobjectsforyourC#programs.

Here,youwillusethepreinstalledclassesofthe.NETframework.

CreatinganObject

Youneedtousethe“new”keywordwhencreatinganobjectusinganexistingclass.

Usually,programmersassignanewobjecttoavariablethatbelongstothesamedatatype

astheobject’sclass.Keepinmindthatthisassignmentproceduredoesn’tcopytheobject

ontothevariable.Rather,thevariableonlycontainsareferencetotheobjectassignedtoit.

Thefollowingcodesnippetwillshowyouhowitworks:

BooksomeBook=newBook();

This example assigns the new instance of the Book class to a variable named “someBook”.Asyoucansee,the“someBook”variablebelongstothe“Book”datatype.

HowtoSettheParametersofaNewObject

C# allows you to assign the parameters of newly created objects. Let’s make some adjustmentstothecodesnippetyou’veseenearlier:

BooksomeBook=newBook(“Biography”,“large”);

ThiscodecreatesanobjectnamedsomeBookandassignstwoparameterstoit.Becauseof

theadjustmentinthecode,theobject’stypebecame“Biography”whileitssizebecame

“large.”

Wheneveryouusethe“new”keyword,the.NETframeworkdoestwothings:

1. Itreservessomememoryforthenewobject.

2. Itinitializestheobject’sdatamembers.

ThisinitializationprocessoccursbecauseofaC#methodknownas“constructor.”Forthe

codesnippetgivenabove,theinitialparametersareinfacttheparametersoftheclass

constructor.

You’lllearnmoreaboutconstructorslater.Sincethevariables“bookType”and“size”of

the“Book”classbelongtothereferencedatatype,yourcomputerprogramcanrecord

themontotheobjectandthe“heap”(i.e.dynamicmemory).

ReleasinganObject

Unlikeotherprogramminglanguages,C#doesn’trequireyoutodestroyobjectsmanually. Thatmeansyoucanreleaseallthememoryconsumedbyyourobjectswithouthavingto perform manual deletions. This functionality became possible because of the CLR, a system that comes with the .NET framework. C# users consider the CLR system a “garbagecollector”becauseitreleasesunusedobjectsontheirbehalf.

WithCLR,yourcomputercanautomaticallydetectandreleaseobjectsthatdon’thaveany

reference.Consequently,thememoryassignedtotheseobjectswillbecomeavailable.

Thisapproachcanhelpyouinpreventingbugsandotherproblems.

Ifyouwanttoreleaseanobject,youneedtodestroyitscorrespondingreference.Here’san

example:

someBook=null;

Thistechniquedoesn’tdeletetheobject.Itsimplyremovesthereferenceoftheobject,

allowingtheCLRsystemtoperformanautomateddeletion.

HowtoAccessanObject’sField

InC#,youshouldusethe“dot”operator(i.e.“.”)whenaccessinganobject’sfield.To

accessafield,youjusthavetoindicatetheobject’sname,placeadot,andenterthefield

youwanttoaccess(e.g.

methodandtheobjectyou’reworkingonbelongtoasingleclass.Youhavetoaccessan

object’sfieldtoextractvalueortoassignanewone.

Whenworkingwithaproperty,youneedtousethe“set”and“get”keywords.The“set”

keywordallowsyoutoassignavaluetoanobjectwhilethe“get”keywordhelpsyouin

extractingvaluefromanobject.

Thecodesnippetgivenbelowwillshowyouhowtouseanobject’sproperty.Itwillcreate

anobjectnamedmyBookandassign“bible”asitsbookType.Then,itwilldisplaythe

informationonthecommandprompt.

).However,youwon’thavetotypeanydotifthe

myBook.size

classBookManipulation

{
{

staticvoidMain()

{
{

BookmyBook=newBook();

myBook.bookType=“Bible”;

System.Console.WriteLine(“Thisisa{0}.”,myBook.bookType);

} }
}
}

HowtoCallanObject’sMethod

IntheC#language,youneedtousetwooperators:thedot(i.e.“.”)andtheinvocation operators(i.e.“()”).Youwon’thavetousethedotoperatorifthemethodandtheobject you’reworkingonbelongtothesameclass.Ontheotherhand,theparenthesesarealways mandatory. To call a method, you just haveto indicate its identifier followed by the invocationoperator.Youmayentersomeparametersbetweentheparenthesesifyouwant toassignoneormoreargumentstothemethod.

WhilewritingC#programs,youcanaddanaccessmodifiertoyourmethods.TheC#

languagesupportsfouraccessmodifiers,namely:protected,internal,private,andpublic.

Thesemodifiersallowyoutorestrictyourcallingabilitieswhenworkingwithamethod.

You’lllearnmoreaboutthesemodifiersinalaterchapter.Atthispoint,youjusthaveto

knowthatthe“public”modifiermakesyourobjectspubliclyavailable.

Thefollowingexamplewillshowyouhowtocallamethod.Asyoucansee,thisexample

isbasedonthecodesnippetyou’veencounteredearlier.

classBookManipulation

{
{

staticvoidMain()

{
{

BookmyBook=newBook();

myBook.size=“large”;

System.Console.WriteLine(“Thisbookis{0}.”,myBook.size);

myBook.Sample();

} }
}
}

TheConstructors

Aconstructorisamethodthatrunsautomaticallywheneveraprogrammercreatesan

object.Themainpurposeofaconstructoristoinitializethedataofthenewlycreated

thiskindofmethod.

Additionally,aconstructorusesthenameoftheclasstowhichitbelongs.Thatmeans

constructorsdon’tuserandomnames.

ImportantNote:C#allowsyoutoassignparameterstoyourconstructors.

ConstructorsandParameters

C#constructorsacceptparameters,justlikeanymethodavailableinthisprogramming

language.Youcansetmultipleconstructorsinyourclasses.However,youneedtomake

surethattheseconstructorshavedifferentnumbersortypesofparameters.Thatmeans

eachconstructorhasauniquesignature.

Rememberthataconstructorrunswheneveryoucreateanobjectinsideaclass.Iftheclass you’reworkingoncontainsmultipleconstructors,youmightwonderwhichconstructor will run while you’re creating an object. C# determines the correct constructor automatically.Youwon’thavetodoanythingmanually.Here,thelanguagecompilerwill select the appropriate constructor based on the parameters that you will use. This principle,knownas“bestmatch”,helpsprogrammersinwritingC#programsquicklyand easily.

Theexamplegivenbelowwillshowyouhowtouseconstructors:

object.Ingeneral,youwon’tgetanyvaluewhileusing

publicclassDevice

{
{

privatestringtype;

privatestringsize;

//Aconstructorwithoutanyparameter.

publicDevice()

{
{

this.type=“laptop”;

this.size=“large”;

 
}
}

//Aconstructorwithtwoparameters.

{
{

this.type=type;

this.size=size;

} }
}
}

Let’sexpandthatcodesnippettofurtherillustratehowconstructorswork.Inthefollowing

sample,youwillcreateanobjectforeachconstructor.Oneoftheseobjectswillbean

undefineddevicewhiletheotheronewillbetaggedasa“tablet.”Then,you’llexecutea

methodcalled“Process”foreachobjectandchecktheoutput.Here’sthecodethatyou

needtotype:

classDeviceManipulation

{
{

staticvoidMain()

{
{

DeviceaDevice=newDevice();

aDevice.Sample();

Console.WriteLine(“Thisisa{0}.”,aDevice.type);

DeviceaDevice=newDevice(“tablet”,“small”);

aDevice.Sample();

Console.WriteLine(“This{0}is{1}.”,aDevice.type,aDevice.size);

} }
}
}

TheStaticDataMembers

Thefieldsyou’veseensofarindicatethestateoftheobjectbeingused.Additionally, these fields are directly linked to specific objects inside a class. In object-oriented programming,youwillencounterspecialtypesofmethodsandfields,whicharelinkedto theclass(ordatatype)andnotwiththeobjectitself.Programmersrefertothiskindof methodorfieldas“staticdatamember”becauseitisnotaffectedbyobjects.Moreover,a staticdatamembercanfunctioninaclassevenwithoutanyobject.Inthispartofthe book,you’lllearnaboutthestaticdatamembersoftheC#language.

Whenwritingaprogram,youneedtodefinestaticmethodsorfieldsusingthe“static”

keyword.Placethiskeywordbeforethefieldtypeorthemethod’svaluetype.C#also

allowsyoutocreatestaticconstructors.Here,youshouldplacethekeywordrightbefore

theconstructor’sname.

UsingaStaticDataMember

Before using static data members in your source codes, you need to understand the differencebetweenastaticmemberandanon-staticmember.Here,let’sthinkofclassesas categoriesofobjectsandobjectsasrepresentativesoftheirrespectivecategory.Inthis assumption,astaticmembershowsthestatusandbehaviorofthecategorytowhichit belongs.Anon-staticmember,ontheotherhand,definesthestatusandbehaviorofeach objectpresentinthecategory.

Asdiscussed

Atthispoint,youshouldknowhowtoinitializebothtypesoffields.

earlier,youneedtoinitializenon-staticfieldswhilecreatinganobject.Rememberthatyou

shouldcompletethisinitializationprocessbyinvokingtheclass’sconstructor.

ImportantNote:Youcannotinitializestaticfieldswhilecreatinganobject.InC#,youcan

onlyinitializeastaticfieldwhileyourprogramisalreadyrunning.

Thecodegivenbelowwillillustratehowstaticdatamemberswork.Inthisexample,the programtriestosolveabasicproblem:itshouldcreateamethodthatrunscontinuously

andincreasesthevalueoftheoutputby1duringeachexecution.Tokeepthingssimple,

let’sstartwith0astheinitialvalue.Thisapproach,whichhelpspeopleinimplementing

uniformnumberingsystems,alsoworksinobject-orientedprogramming.

Forthisexample,thenameofthemethodis“NextOutput().”Thismethodexistsinsidea

classnamed“Sample”.ThisclasscontainsafieldcalledcurrentOutputfromthe“double”

datatype.Asitsnameimplies,currentOutputholdsthelatestvaluethatthemethodhas

returned.Asaprogrammer,youwanttwothingstooccurinsidethebodyofthemethod:

(1)increasethefield’svalue;and(2)returnthenewvalueastheresult.

ThereturnedvalueinvolvedhereisnotaffectedbytheobjectsinsidetheSampleclass.

Thus,thefieldandmethodusedbytheprogramarestatic.Here’sthecode:

publicclassSample

{
{

//Thisisthestaticfield.Itholdsthecurrentoutputoftheprogram.

PrivatestaticdoublecurrentOutput=0;

//Thispartofthecodedeniestheclassinstantiationintentionally.

PrivateSample()

//Thisstaticmethodtakesthenewvalues.

PublicstaticdoubleNextOutput()

{
{

currentOutput++;

returncurrentOutput;

} }
}
}

YoumighthavenoticedthattheSampleclasshasaconstructornamed“private.” Usingthisconstructormaybeconfusingatfirst.However,youwillbeabletomasterit quickly. Remember this simple rule: you can’t instantiate classes that contain private constructorsonly.Theseclassesonlyhavestaticdatamembersandarecalled“utility classes.”

Now,let’screateabasicprogramthatusestheSampleclass:

classSampleManipulation

{
{

staticvoidMain()

{
{
Console.WriteLine(“Let’scount:[1…3]:{0},{1},{2}”,Sample.NextOutput(), Sample.NextOutput(),Sequence.NextOutput());
Console.WriteLine(“Let’scount:[1…3]:{0},{1},{2}”,Sample.NextOutput(),

Console.WriteLine(“Let’scount:[1…3]:{0},{1},{2}”,Sample.NextOutput(),

Console.WriteLine(“Let’scount:[1…3]:{0},{1},{2}”,Sample.NextOutput(), Sample.NextOutput(),Sequence.NextOutput());
Sample.NextOutput(),Sequence.NextOutput());

Sample.NextOutput(),Sequence.NextOutput());

} }
}
}

This program prints “1”, “2”, and “3” onto the command prompt by calling the NextOutput()methodthreetimes.Yourcommandpromptshouldlooklikethis:

and “3” onto the command prompt by calling the NextOutput()methodthreetimes.Yourcommandpromptshouldlooklikethis:

ImportantNote:Becausetheconstructorofthisclassis“private”,youwillreceivea

compile-timeerrorifyouwillcreatemultiplesequencesinsidethisclass.

TheSystemClassesofC#

Nowthatyouknowhowtocreateanduseobjects,youarereadytolearnmoreaboutthe

systemclassesofthe.NETframework.Inthispartofthebook,you’lllearnhowsystem

classescanhelpyouincreatingnewcomputerprograms.

System.Environment

This is one of the most basic classes of the .NET framework. Basically, the System.Environmentclasscontainspowerfulmethodsandfields,whichcanhelpyouin gettingmoreinformationabouttheOSandhardwareyouareusing.Additionally,these methodsandfieldsallowyoutocommunicatewiththe“environment”ofyourcomputer programs.TheSystem.Environmentclassprovidesthefollowingfunctionalities:

Itcangiveyoudetailedinformationaboutthecomputersuchasthenumberof

processors,thenameofthenetwork,theOSversion,theactivefiledirectory,etc.

Itallowsyoutoaccessvariablesandpropertieslocatedoutsidetheprogram.

Inthefollowingexample,you’llseehowtoapplytheSystem.Environmentclassinyour programs. This approach assists programmers in creating applications with topnotch performance.Thepropertycalled“TickCount”willdeterminethetimerequiredtoexecute theprogram’ssourcecode.Here’sthecode:

classExample

{
{

staticvoidMain()

{
{

doubleamount=0;

doublebeginning=Environment.TickCount;

//Theprogramwilltestthiscodesnippet.

For(doublex=0;x<1000000;x++)

{
{

amount++;

}
}

doubleconclusion=Environment.TickCount;

System.Console.WriteLine(“The required time is {0} milliseconds.”, (conclusion – beginning)/1000.0);
System.Console.WriteLine(“The required time is {0} milliseconds.”, (conclusion –

System.Console.WriteLine(“The required time is {0} milliseconds.”, (conclusion –

System.Console.WriteLine(“The required time is {0} milliseconds.”, (conclusion – beginning)/1000.0);
beginning)/1000.0);

beginning)/1000.0);

}
}
}
}

TickCount,whichisastaticpropertyoftheEnvironmentclass,measuresthetimethathas

elapsedsincethemachinewasbootedupuntilthemethodwasinvoked.TheTickCount

propertymeasuresthetimeusingmilliseconds.Withthisproperty,youcanidentifythe

lengthoftimeneededinexecutingacode.

Ifyouwillcompileandrunthecodegivenabove,yourcommandpromptwillshowyou

somethinglikethis:

somethinglikethis:

ImportantNote:Inthisexample,youusedtwomembersoftwodifferentclasses.These

membersareTickCount(i.e.fromtheSystem.Environmentclass)andWriteLine(i.e.from

theSystem.Consoleclass).

System.String

ThisclassrepresentsstringvaluesoftheC#language.Rememberthatstringsaresimilar

totheprimitivedatatypesofC#(e.g.Boolean,integers,characters,etc.).

System.Math

This class can help you in performing basic mathematical operations. Basically, System.Mathcontainsmethodsthatcansolveexponential,logarithmic,andtrigonometric problems.

System.Random

Insomecases,youneedtogeneraterandomnumbersforyourcomputerprograms.Let’s

assumethatyouneedtogetsixrandomnumbersbetween1and49.IntheC#language,

youcanaccomplishthistaskusingtheclasscalledSystem.Randomandabuilt-inmethod

calledNext().

BeforeusingtheSystem.Randomclass,youneedtogenerateanobject(orinstance)inside it.Thesystemwillassignavaluetothatnewlycreatedobject.Then,youcangenerate

randomnumberswithinthe[0–x]rangebyinvokingtheNext(x)method.Asyoucansee,

thismethodcanproducea“0”butalwaysgeneratesanumberthatissmallerthan“x”.

Thus,ifyouwanttogetanumberbetween1and49,theexpressionthatyoushoulduseis

Next(50).

Here’s a basic program that produces six random numbers between 1 and 49. This programwillcompletetheassignedtaskusingtheSystem.Randomclass.

classRandomNumber

{
{

staticvoidMain()

{
{

randomnumber=newRandom();

for(doublesample=1;sample<=6;sample++)

{ doublerandomValue=number.Next(50); System.Console.WriteLine(“{0},randomValue); } } }
{
doublerandomValue=number.Next(50);
System.Console.WriteLine(“{0},randomValue);
}
}
}

HowtoCreateaPasswordUsingthe“Random”Class

The“randomvaluegenerator”ofthe.NETframeworkisextremelypowerful.Itcanhelp you to accomplish a wide range of tasks. In this part of the book, you’ll use the

System.Randomclasstocreateastrongpassword.Thispasswordis8to16characters

longandcontainsatleastonenumber,twouppercaseletters,twolowercaseletters,and

threespecialcharacters.Tocreatethiskindofpassword,youshouldusethealgorithms

listedbelow:

1. Createablankpassword.Then,runthe.NETframework’s“valuegenerator.”

2. Generatetworandomuppercaselettersandplacethematrandompositionsinthe

newpassword.

3. Generatetworandomlowercaselettersandplacethematrandompositionsinthe

newpassword.

4. Generatearandomnumberandplaceitinarandomspotinthenewpassword.

5. Generatethreespecialcharactersrandomlyandplacetheminrandomspotsinthe

newpassword.

6. Thepasswordhaseightcharactersatthispoint.Toaddmorecharacterstoit,you

shouldinsertarandomcharacteratarandompositioninarandomnumberoftimes.

Let’sconvertthesealgorithmsintoactualcodes:

classPassword

{
{

conststringUppercaseLetters=“ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

conststringLowercaseLetters=“abcdefghijklmnopqrstuvwxyz”;

conststringNumbers=“0123456789”;

conststring=SpecialCharacters=“~@!#$%^&*()_+’=/|;:.,><?”;

conststringAllCharacters=

UppercaseLetters+LowercaseLetters+Numbers+SpecialCharacters;

staticRandomsample=newRandom();

staticvoidMain()

{
{

StringBuildernewpassword=newStringBuilder();

//Thiscodefragmentselectstwouppercaselettersrandomly.

for(doublex=1;x<=2;x++)

{
{

charuppercaseLetter=GenerateChar(UppercaseLetters);

InsertAtRandomPosition(newpassword,uppercaseLetter);

 
}
}

//Thispartofthecodegeneratestwolowercaselettersrandomly.

For(intx=1;x<=2;x++)

{
{

charlowercaseLetter=GenerateChar(LowercaseLetters);

InsertAtRandomPosition(newpassword,lowercaseLetter);

}
}

//Thiscodeblockchoosesarandomnumber.

intnumber=GenerateChar(Numbers);

InsertAtRandomPosition(newpassword,number);

//Thispartrandomlyselectsthreespecialcharacters.

for(intx=1;x<=3;x++)

{
{

charspecialCharacter=GenerateChar(SpecialCharacters);

InsertAtRandomPosition(newpassword,specialCharacter);

}
}

doublecounterrnd.Next(9);

for(intx=1;x<=counter;x++)

{
{

charspecialCharacter=GenerateChar(AllCharacters);

 

InsertAtRandomPosition(newpassword,specialCharacter);

}
}

System.Console.WriteLine(newpassword);

}
}

privatevoidInsertAtRandomPosition(StringBuildernewpassword,charnewcharacter)

{
{

intrandomSpot=rnd.Next(newpassword.Length+1);

newpassword.Insert(randomSpot,newcharacter);

} {
}
{

privatecharGenerate(stringavailableCharacters)

{
{

intanyIndex=rnd.Next(availableCharacters.Length);

charrandomCharacter=availableCharacters[anyIndex];

returnrandomCharacter;

} }
}
}

Thefirstpartofthecodedeclaredseveral“constants.”IntheC#language,aconstantisan unchangeablevariablethatrequiresaninitialvalueduringitsdeclaration.Youhaveto declareconstantsusingthe“const”modifier.Forthisexample,youusedsomeconstantsto define a number and several strings, which were utilized multiple times inside the computerprogram.

Thisapproachallowsyoutominimizeyourcodes:youdon’thavetorepeatstatements

anymore.Additionally,itallowsyoutoperformquickchangestoyourcodeswithout

retypinganything.Forinstance,ifyoudecidedtoremovetheequalsign(i.e.“=”)fromthe

listofspecialcharacters,youcanaccomplishitjustbyworkingonasinglestatement(i.e.

theconstantthatholdsthespecialcharacters).

Chapter6:HowtoDefineClassesinC#

Thischapterwillteachyouhowtocreateyourownclasses.Byreadingthismaterial,

you’llknowhowtosetthefields,properties,andconstructorsofacustomizedclass.

Additionally,youwillknowmoreinformationaboutmethodsandaccessmodifiers.

Classes–TheBasics

Aclassdefinestheobjectsanddatatypesthatyoucanuseinyourprograms.Anobject

(alsoknownasan“instance”ofaclass)containstheactualinformation.Thisinformation

definesthestateofitscontainer(i.e.theobjectthatholdsit).

Classesalsodescribetheobjects’behavior. Asyouknow, behaviorsarepresentedas actions that an object can perform. In object-oriented programming, you should use methodstodescribethebehaviorofyourobjects.

TheComponentsofaClass

Eachclassconsistsofthefollowingparts:

Declaration–Thislinedeclarestheclass’sidentifier(e.g.

classExample

).

Body–Justlikemethods,classeshaveasinglebody.Youneedtodefinethispart right after the declaration. The body of a class is a statement or a group of statementsfoundbetweenapairofcurlybraces.Here’sanexample:

classExample

{
{

//Thisisthebodyofthe“Example”class.

}
}

Constructor–Thispartallowsyoutocreatenewobjects.Thecodesnippetgiven

belowisanexcellentexample:

publicSample()

{
{

//Insertsomelineshere.

}
}

Fields–Thesearevariablesthatyoushoulddeclarewithintheclass.Programmers also use the term “member variables” when referring to the fields of a class. Basically,fieldscontainvaluesthatrepresenttheexactstateoftheobjectthey’re pointingto.

Properties–Thispartdescribestheattributesofaclass.Often,programmerswrite

classpropertiesinsidethefieldofanobject.

Methods – Basically, a method is a named block of executable code. It can complete certain tasks and allow objects to attain their respective behavior. In addition,itcanexecutethealgorithmspresentinyourcodes.

Theexamplegivenbelowshowsyouhowtocreateaclass.Asyouwillsee,thisclasshas

allofthepartslistedearlier.

allofthepartslistedearlier. classMusicalInstrument //Thisistheclassdeclaration. {

classMusicalInstrument

//Thisistheclassdeclaration.

{

//Thisbracketsignalsthestartoftheclass’sbody.

stringinstrumentType;

//Thislinedeclaresanewfield.

publicMusicalInstrument() //Thislinedeclaresanemptyconstructor.

public MusicalInstrument(string instrumentType) // This line creates another constructorfortheclass.
public MusicalInstrument(string instrumentType) // This line creates another

public MusicalInstrument(string instrumentType) // This line creates another

public MusicalInstrument(string instrumentType) // This line creates another constructorfortheclass.
constructorfortheclass.

constructorfortheclass.

{
{

this.instrumentType=instrumentType;

}
}

stringInstrumentType//Here,youaredeclaringaproperty.

{
{

get{returninstrumentType;}

 

set{instrumentType=value;}

}
}

staticvoidInstrument() //Thislinedeclaresanewmethodfortheclass.

{
{

System.Console.WriteLine(“Thisisa{0}.”,instrumentType??);

ClassesandObjects

Inthepreviouschapter,youlearnedhowtocreateanduseclassobjects.Now,you’lllearn

moreaboutthistechnique.

CustomClasses

Beforeusinganyclass,youneedtocreateanobjectinsideit.Youcanaccomplishthistask

usingthe“new”keywordandtheconstructorspresentintheclassyou’reworkingon.

C#preventsyoufrommanipulatingobjectsdirectly.Inthisprogramminglanguage,you

havetoassignanobjecttoavariablebeforedoinganymanipulation.Thatmeansyouwill

accessand/orusetheobjectthroughthevariabletowhichitisassigned.

ImportantNote:Toaccessthepropertiesandmethodsofanobject,youneedtoindicate

theobject’sidentifierandusethedotoperator.

MoreInformationAboutObjects

Eachobjectinthe.NETframeworkconsistsoftwoparts:(1)theactualpart;and(2)the

referencepart.The“actual”partcontainstheinformationabouttheobjectandisstored inside the heap (also known as “dynamic memory”) of the computer’s OS. The “reference”part,ontheotherhand,existsinthecomputerprogram’sexecutionstack.The executionstackisthepartofthecomputermemorythatholdsthelocalvariablesand methodparameters.

For instance, let’s assume that you created a class named “Instruments.” This class containsthetypes,names,andsizesofdifferentmusicalinstruments.Then,let’ssaythat you created a variable inside the class and named it “instrument.” The “instrument” variablewillserveasareferenceforanobjectandwillbestoredinthecomputer’sheap.

ImportantNote:Ifyouwanttocreateavariablewithoutassociatingittoanyobject,you

havetogiveitthe“null”value.The“null”keywordinformsthelanguagecompilerthat

yourvariabledoesn’tholdanyvalue.

HowtoOrganizeYourClasses

WhenusingC#,there’sjustonerulerelatedtosavingcustomizedclasses:saveyour classes in a “.cs” file. Files that belong to this type allow you to define C# classes. Technically,youcansaveallofyourclassesinjustasinglefile.Thecompilerwillwork fineandyouwon’treceiveanyerrormessage.However,itwouldbebestifyouwillsave eachclassinaseparatefile.Thisapproachhelpsyouinkeepingyourclassesorganized. Obviously,you’llexperiencesomeproblemsinfindingacertainclassifallofyourclasses arestoredinonefile.

HowtoUseaNamespace

IntheC#language,anamespaceisasetofclassesthatarelogicallyrelated.Itcontains

structures,interfaces,classes,andotherkindsofinformation.Actually,anamespacecan

alsostoreothernamespaces.Youcancombineyourclassesintoanamespaceregardlessof

theirlocationinthecomputer’smemory.

Ifyouwanttouseanamespaceinyourcodes,youneedtoadda“using”directive.Most

programmerswritetheirusingdirectivesinthefirstfewlinesofthe.csfile.Afterinserting

thedirective,youshoulddeclarethenamespacesthatyouwanttouse.

TheAccessModifiers

Asdiscussedinthepreviouschapter,C#supportsfourmodifiers:private,public,internal,

andprotected.Thesemodifiersallowyoutocontrolthe“visibility”ofyourclasselements.

Let’sdiscusseachmodifierindetail:

Private–Thismodifierplacesthehighestlevelofrestriction.Ifanelementis

taggedas“private”,itwillbeinaccessibletootherclasses.TheC#languageusesit

asthedefaultaccessmodifier.Thus,ifyouwon’tindicatethe“accessibilitylevel”

ofanelement,thesystemwilltagitas“private.”

Public–Usethismodifierifyouwantanelementtobeaccessibletoallofyour

classes.The“public”keywordmeansthattherearenolimitationsregardingthe

object’svisibility.

Internal–Ifanelementhasthismodifier,itwillonlybeaccessibletofilesthat

belongtothesameproject(alsoknownasassembly).

Protected–Thismodifierpreventsusersfromaccessinganelement.However,it

allowsdescendantclassestouseandaccesstheelementinvolved.

HowtoDeclareaClass

C#implementsstrictrulesregardingclassdeclarations.Youwillsurelygetcompile-time

andruntimeerrorsifyouwilldeclareclassescarelessly.Tomakesurethatyouwon’tget

anyerror,youshouldusethefollowingsyntax:

<modifier><class><name_of_the_class>(e.g.publicclassVehicles

TheBodyofaClass

Youshouldwritethebodyofyourclassrightafteritsidentifier.Keepinmindthatthe “body” is the part that contains the executable codes. Just like other programming languages,youshouldwritethispartinsideapairofcurlybraces.

The“this”Keyword

InC#,the“this”keywordtagsthecurrentelement(e.g.object)asareferenceforthenext

process.Youcanconsiderthisasatoolforaccessingthecontentsofaclass.Hereare

someexamples:

someexamples: ) this.sampleField;

)

this.sampleField;

//Usethissyntaxtoaccessaparticularfield.

this.sampleMethod();

//Usethissyntaxtorunamethod.

this(8,9);

//Usethissyntaxtotriggeraconstructorthatcontainstwoparameters.

TheFields

An object represents things in the physical world. To define an object, you should concentrateonitsattributes,whicharelinkedtothepurposeofyourcomputerprogram.

Youneedtostoretheseattributesintheclassdeclarationusingspecialvariables.These

specialvariables,knownasfields,definethestatusoftheobjectyou’reworkingon.

HowtoDeclareaField

C#requiresyoutodeclareyourfieldsinthebodyofaclass.Thecodegivenbelow

declaresmultiplefields:

classExample

{ doublesalary; charfavoriteLetter; stringyourName; }
{
doublesalary;
charfavoriteLetter;
stringyourName;
}

AField’sScope

Thescopeofanyfieldbeginsfromthepartwhereitiswrittenandcontinuesuntiltheend

oftheclass’sbody.

InitializingaField

C#allowsyoutosetthevalueofyournewlycreatedfields.Thesyntaxthatyouneedto

useissimilartothatofordinaryvariables:

<modifier><type_of_field><name_of_field>=<value>;

ImportantNote:Makesurethattheinitialvalueiscompatiblewiththefieldyouareusing.

Asyouknow,C#implementsstrictrulesregardingthecompatibilityofdatatypes.Check

thefollowingexample:

classSample

{ intpayment=5000; charletter=‘x’; string[]instruments=newstring[]{“guitar”,“drums”};
{
intpayment=5000;
charletter=‘x’;
string[]instruments=newstring[]{“guitar”,“drums”};
VehiclesmyVehicle=newVehicles();
}

TheDefaultValueofaField

Wheneveryoucreateanobjectinsideanyclass,thesystemallocatesmemoryforthefields

ofthatnewobject.Thesystemdoesthisbysettinganinitialvaluetoeachfield.Ifyoudo

notsetthedefaultvaluesforyourclassfields,theywillgetthevaluesspecifiedbythe

.NETframework.

Thisfunctionalityisthemaindifferencebetweenfieldsandlocalvariables.Thelanguage

compilerwillgiveyouanerrormessageifanyofyourlocalvariablesdonotcontaina

value.

HowtoCustomizetheDefaultValues

TheC#languageallowsyoutosetthedefaultvaluesofyourfields.Withthisfeature,you

canboostthecleanlinessandreadabilityofyoursourcecodes.Let’susethefieldsyou’ve

seenearlierasexamples:

classSample

{ intpayment=0; charletter=null; string[]instruments=null; VehiclesmyVehicle=null; }
{
intpayment=0;
charletter=null;
string[]instruments=null;
VehiclesmyVehicle=null;
}

Conclusion

Thankyouforreadingthisbook,IhopeitwasabletohelpyoumasterthebasicsofC#.

Now,youshouldrereadthisbooktoreinforceyourmemoryandcontinuewritingyour

ownprograms.Keepinmindthatyouwon’tbecomeagreatprogrammerifyoudon’t

practiceyourprogrammingskills.Thecodesnippetsincludedinthisbookcanserveas

excellentguides.Itwouldbebestifyouwillusethemastemplatesinwritingyourown

computerprograms.

Finally,ifyouenjoyedthisbook,pleasetakethetimetoshare yourthoughtsandpostapositivereviewonAmazon. It’dbe greatlyappreciated!

Thankyouandgoodluck!