Table Of ContentIntroductory Programming in C#
Release 1.0
Andrew N. Harrington and George K. Thiruvathukal
May29,2012
CONTENTS
1 Context 1
1.1 IntroductiontotheNotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 CommentsonMilesChapter1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2 C#DataandOperations 3
2.1 DevelopmentTools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 LabExercise: Editing,Compiling,andRunning . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 CommentsonMilesSimpleData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.4 DivisionandRemainders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.5 SubstitutionsinConsole.WriteLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.6 LearningtoSolveProblems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.7 Lab: DivisionSentences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.8 Homework: GradeCalculation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3 DefiningFunctionsofyourOwn 23
3.1 SyntaxTemplateTypography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 AFirstFunctionDefinition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 MultipleFunctionDefinitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.4 FunctionParameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.5 MultipleFunctionParameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.6 ReturnedFunctionValues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.7 TwoRoles: WriterandConsumerofFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.8 LocalScope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.9 StaticVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.10 NotusingReturnValues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4 BasicStringOperations 37
4.1 StringIndexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2 SomeInstanceMethodsandtheLengthProperty . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 ACreativeProblemSolution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.4 Lab: StringOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5 Decisions 43
5.1 ConditionsI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.2 SimpleifStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.3 if-elseStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
5.4 MoreConditionalExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.5 MultipleTestsandif-elseStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.6 If-statementPitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
i
5.7 CompoundBooleanExpressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
6 WhileLoops 55
6.1 While-Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2 While-StatementswithSequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.3 InteractivewhileLoops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.4 Short-Circuiting&&and|| . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.5 WhileExamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.6 MoreStringMethods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.7 AlgorithmsusingWhile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.8 Do-WhileLoops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.9 NumberGuessingGameLab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.10 Homework: GradeCalculationfromIndividualScores . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.11 Lab: UsingMonoDevelop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.12 Lab: VersionControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7 ForeachLoops 107
7.1 foreachSyntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.2 foreachExamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
8 ForLoops 109
8.1 For-StatementSyntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.2 ExamplesWithforStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
9 Files 119
9.1 FileSyntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.2 GradeFileHomework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
10 Arrays 127
10.1 OneDimensionalArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
10.2 MusicalScalesandArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
10.3 LinearSearching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
10.4 SortingAlgorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
10.5 BinarySearching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
10.6 Lab: Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
10.7 Lab: Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
10.8 Multi-dimensionalArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
11 Lists 159
11.1 ListSyntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
11.2 .NetLibrary(API) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
12 Dictionaries 163
12.1 DictionarySyntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
12.2 DictionaryEfficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
12.3 DictionaryExamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
12.4 Lab: FileDataandCollections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
13 Classes 171
13.1 AFirstClassExample: Rational . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
13.2 ClassesAndStructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
13.3 ClassExamples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
13.4 BookListAssignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
13.5 MercurialandTeamwork. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
ii
14 Interfaces 189
14.1 FractionsRevisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
14.2 CSProjRevisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
14.3 GroupGameProject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
15 Testing 201
15.1 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
15.2 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
15.3 TestingtheConstructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
15.4 TestingRationalComparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
15.5 TestingRationalArithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
15.6 TestingRationalConversions(toothertypes) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
15.7 TestingtheParsingFeature. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
15.8 RunningtheTests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
16 Acknowledgements 207
17 ChangeLog 209
18 TODO’s 211
Index 213
iii
iv
CHAPTER
ONE
CONTEXT
1.1 Introduction to the Notes
These notes are designed for Comp 170. They are closely tied to the excellent C# introduction in Rob Miles’ free
onlineC#YellowBook.
Thesenoteswillfollowmostlythesameorder,addingsomeextraexplanations,examples,andchallenges,andintro-
ducetheMonoopensourceimplementationofC#.
ThecontentherewillbeinterspersedwithcommentsaboutwheretolookatpartsofMilesbook,withclarificationsof
thebookandcommentsaboutwhatisnotimportantforabeginnerinthebook.
Computerprogramsaredesignedtorunonacomputerandsolveproblems. Thoughtheinitialproblemswillbetiny
andoftensilly,theywillserveaslearningtoolstoprepareforsubstantiveproblems.
1.2 Comments on Miles Chapter 1
MilesChapter1onComputersandProgramsmakesagoodintroductionandgivescontext. Readforthegroundingit
gives.
ThechaptermakessomereferencetoMicrosoft,theoriginalcreatorofC#,anditsVisualStudiosoftwaredevelopment
environment,whichworksonlyonWindowsmachines,andcostsalotifyouarenotastudent. Theoptionaltextby
Lewis discussed Visual Studio at some length. The next section of these notes will introduce an alternative to the
Microsoft environment: Mono, which is free, open-source software that makes C# available for multiple platforms:
Windows,Mac,orLinuxmachines.
1
IntroductoryProgramminginC#,Release1.0
2 Chapter1. Context
CHAPTER
TWO
C# DATA AND OPERATIONS
2.1 Development Tools
2.1.1 About Software Development Kits (SDKs)
Asoftwaredevelopmentkit(SDK)isasetoftoolsfordevelopinginaparticularprogramminglanguage(inourclass,
C#).Developinginalanguagemeanseverythingfromcompilingtorunningand(whenthingsgowrong)todebugging
programs.
TheMicrosoftSDKistheproprietaryimplementationof.Net.ItrunsonlyonWindowsandistheprimarydevelopment
frameworkforallthingsMicrosoft.
TheMonoProjectSDK<http://mono-project.com>isthefree/opensourceequivalentimplementationoftheMicrosoft
SDK.Itrunsonallmajorplatforms(includingWindows)andisneededinsituationswhereyouwanttodevelop.Net
applicationsonnon-Windowsplatforms.
Asaninterestingaside,thecompanywhosedevelopersleadtheworkontheMonoSDKareworkingoncommercial
toolsthatallowyoutodevelop/runapplicationswrittenin.NetonAppleiOSandAndroidmobiledevices(phonesand
tablets).
2.1.2 About Integrated Development Environments (IDE)
Whilejustabouteverythingyouneedtocreateprogramscan,indeed,befoundintheSDK,itisnotlongbeforeyou
wishtherewerean“appforthat”sotospeak. Whilemostprogrammerswhodevelopedcode(likeyourinstructors)in
the1970s-1990slearnedtoprogramdirectlywiththeSDKusingthecommandline, today’sprogrammerslargelyto
preferworkinginanIDE.
TherearetwomajorIDEsfor.Netdevelopment,whichweexplainbrieflybelow:
• VisualStudioistheMicrosoftIDEthatinterfacesdirectlytotheMicrosoftSDK.
• MonoDevelopisthefree/opensourceIDEfordevelopingapplicationsusingtheMonoSDKonWindowsand
allotherplatforms(inparticular,LinuxandOSX).
Inaddition, thereisanotherWindows-specificIDE,SharpDevelop, thatinspiredthecreationofMonoDevelop. Itis
still actively maintained and provides a somewhat “lighter weight” alternative to Visual Studio for Windows users.
LikeMonoDevelop,itisaimedatdeveloperswhowouldpreferamorefree/opensource“friendly”version.
2.1.3 Our Approach
Intheinterestofprovidingaconsistentexperienceforourstudents,wewillbeusingMono(theSDK)andMonoDe-
velop (the IDE) for everything we demonstrate in class. We will also be encouraging you to use it for your work,
3
IntroductoryProgramminginC#,Release1.0
especiallyifyouareinterestedinnon-Microsoftplatforms.
OurnotesassumeforthemostpartthatyouareworkingwithMonoandMonoDevelop. Inmostcases,whatweare
showingyouinMonoandMonoDevelopwilltranslatealmostasistotheMicrosoftequivalents. However,thereare
sometools,suchasthecsharpinterpreter,thathavearoughanaloginMicrosoft’stoolsbutinasomewhatlimited
form. AsthereissignificantevolutionofboththeMicrosoftandMonotoolchains–afancywordwewantyoutoknow
andamoreelegantwayofsayingSDK–we’llissueupdatestothesenotes.
2.1.4 Installing Mono
BecausetheMonoProjectwebpageisknowntochangefrequently,theseinstructionsaredesignedtobeasgenericas
possible. Ifyouhaveanyquestions,youshouldcontacttheinstructorsimmediatelyorseektutoringhelp.
2.1.5 OS X
1. Goto<http://mono-project.com>.
2. LookfortheMonodownloadslink. YouwanttogetthelateststableversionofMonoforOSX.Forthisclass,
youneedversion2.10orlater.
3. YoumayseealinktodownloadRuntimeorSDK.MakesureyouselectSDK.
4. ForOSX,theSDKisdistributedasaDMGdiskimage. You’llneedtodownloadthisimageanddouble-click
it. Opentheimageandruntheinstaller. Administrativeprivilegesarerequiredtoruntheinstaller,soifyoudo
notknowthisinformation,pleasestophere.
5. Onceinstallationiscompleted,youhaveeverythingneededtostartusingtheIDE,MonoDevelop.
6. Nowgoto<http://mono-develop.com>.
7. AswithMono,weneedtolookforthedownloadslink. Youshoulddownloadthestableversion.
8. AswithMono,youwillseeaDMGfile,whichyoushoulddownloadanddouble-clicktomountonyourdesktop.
9. Thistime,youwillseeanAppforMonoDevelop,whichyoucandraganddropintotheApplicationsfolder.
HereishowtodoaquicksanitycheckofyourMonosetup:
1. GotoApplications->UtilitiesandlaunchtheTerminalapplication.(Terminalishowyougettoacommand-line
shellinOSX.)
2. You’llseeapromptthatlookslikethiscomputername:folder user$.ThismeansthatTerminalisready
forinput.
3. Typewhich csharpandhitenter/return. Youshouldsee/usr/bin/csharpasoutput. csharpisthe
C#interpreter.
4. Type which dmcs and hit enter/return. You should see /usr/bin/dmcs as output. dmcs is one of the
interfacestotheC#compiler.
5. Ifthetwoprecedingstepsweresuccessful, youcanlaunchMonoDevelopbydouble-clickingtheiconinyour
Applicationsfolder. (Youwon’tknowwhattodowithityet,butatleastyoucanverifythatitlaunchescorrectly
andthenuseCommand-Qtoexit.)
2.1.6 Windows
1. Goto<http://mono-project.com>.
4 Chapter2. C#DataandOperations
Description:Introductory Programming in C# Release 1.0 Andrew N. Harrington and George K. Thiruvathukal May 29, 2012