0% found this document useful (0 votes)
40 views68 pages

1 08 00407 000 04 18 19 Sample

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views68 pages

1 08 00407 000 04 18 19 Sample

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

TRAINING MATERIALS FOR IT PROFESSIONALS


EV
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d
uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n

Object Oriented
Pr

PY
oh

Programming in C#
bii
te

Student Workbook
d
Object-Oriented Programming in C#
Rev. 4.8.5
EV
Student Guide
U
na

AL
Information in this document is subject to change without notice. Companies, names and data used
ut

in examples herein are fictitious unless otherwise noted. No part of this document may be
reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose,
ho

without the express written permission of Object Innovations.


riz

U
Product and company names mentioned herein are the trademarks or registered trademarks of their
ed

respective owners.
R

AT
ep
ro
d uc

IO
tio

™ is a trademark of Object Innovations.


n
or

Authors: Robert J. Oberg, Howard Lee Harkness


N
D

Special Thanks: Marianne Oberg, Sharman Staples, Paul Nahay


is
tri

Copyright ©2019 Object Innovations Enterprises, LLC. All rights reserved.


C
bu
tio

Object Innovations
O
877-558-7246
n

www.objectinnovations.com
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC ii


All Rights Reserved
PY
O
d
te
bi
C
i
oh
Pr
N
n
tio
bu
IO
tri
is
AT
D
or
n
tio
uc
U d
AL
ro
ep
R
ed
EV
riz
ho
ut
na
U
Table of Contents (Overview)
Chapter 1 Introduction to .NET
Chapter 2 First C# Programs
EV
Chapter 3 Data Types in C#
Chapter 4 Operators and Expressions
U

Chapter 5 Control Structures


na

AL
Chapter 6 Object-Oriented Programming
ut
ho

Chapter 7 Classes
riz

Chapter 8 More about Types


U
ed

Chapter 9 Methods, Properties and Operators


R

AT
Chapter 10 Characters and Strings
ep

Chapter 11 Arrays and Indexers


ro
d

Chapter 12 Inheritance
uc

IO
Chapter 13 Virtual Methods and Polymorphism
tio

Chapter 14 Formatting and Conversion


n
or

Chapter 15 Exceptions
N
D

Chapter 16 Interfaces
is
tri

Chapter 17 .NET Interfaces and Collections


C
bu

Chapter 18 Delegates and Events


tio

Chapter 19 Introduction to Windows Forms


O
n

Chapter 20 Newer Features in C#


Pr

PY
oh

Appendix A Learning Resources


i bi

Electronic File Supplements


te
d

Supplement1.pdf Using Visual Studio 2019


Supplement2.pdf Language Integrated Query (LINQ)
Supplement3.pdf Unsafe Code and Pointers in C#

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC iii


All Rights Reserved
Directory Structure

 The course software installs to the root directory


EV
C:\OIC\CSharp.
 Example programs for each chapter are in named
U

subdirectories of chapter directories Chap01, Chap02, and so


na

AL
on.
ut
ho

 The Labs directory contains one subdirectory for each lab,


riz

U
named after the lab number. Starter code is frequently
ed

supplied, and answers are provided in the chapter directories.


R

AT
 The CaseStudy directory contains a case study in multiple
ep
ro

steps.
d uc

 The Demos directory is provided for performing in-class


IO
tio

demonstrations led by the instructor.


n

 Supplementary course content is provided in PDF files in the


or

N
Supplements directory. Code examples for the supplements
D
is

are in directories Supp1, Supp2 and Supp3.


tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC iv


All Rights Reserved
Table of Contents (Detailed)

Chapter 1 Introduction to .NET .................................................................................... 1


What Is .NET? .................................................................................................................... 3
EV
Libraries and Tools ............................................................................................................. 4
Application Models ............................................................................................................ 5
Managed Code .................................................................................................................... 6
.NET Programming in a Nutshell ....................................................................................... 7
U
na

Visual Studio 2019.............................................................................................................. 8


AL
Visual Studio Sign In.......................................................................................................... 9
ut

Creating a Console Application........................................................................................ 10


ho

Configure Your New Project ............................................................................................ 12


riz

Program.cs Starter Code ................................................................................................... 13


U
Using the Visual Studio Text Editor................................................................................. 14
ed

IntelliSense ....................................................................................................................... 15
Build the Project ............................................................................................................... 16
R

AT
Run the Project.................................................................................................................. 17
ep

Pausing the Output............................................................................................................ 18


ro

Visual C# and GUI Programs ........................................................................................... 19


d

.NET Documentation ........................................................................................................ 20


uc

Summary ........................................................................................................................... 21
IO
tio

Chapter 2 First C# Programs .......................................................................................... 23


n

Hello, World ..................................................................................................................... 25


or

Program Structure ............................................................................................................. 26


N
Namespaces ...................................................................................................................... 29
D

Exercise............................................................................................................................. 30
is

Answer .............................................................................................................................. 31
tri

Variables ........................................................................................................................... 32
C
bu

Expressions ....................................................................................................................... 33
tio

Assignment ....................................................................................................................... 34
O
Calculations Using C# ...................................................................................................... 35
n

Sample Program................................................................................................................ 36
Pr

More about Output in C# .................................................................................................. 37


PY
oh

Input in C# ........................................................................................................................ 38
More about Classes........................................................................................................... 39
i bi

InputWrapper Class .......................................................................................................... 40


te

Echo Program ................................................................................................................... 41


d

Using InputWrapper ......................................................................................................... 42


Multiple Files in Visual Studio......................................................................................... 43
The .NET Framework ....................................................................................................... 44
Lab 2 ................................................................................................................................. 46
Summary ........................................................................................................................... 47

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC v


All Rights Reserved
Chapter 3 Data Types in C#............................................................................................. 51
Strong Typing ................................................................................................................... 53
Typing in C# ..................................................................................................................... 54
C# Types ........................................................................................................................... 55
Integer Types .................................................................................................................... 56
EV
Integer Type Range........................................................................................................... 57
Integer Literals.................................................................................................................. 58
Floating Point Types......................................................................................................... 59
Floating Point Literals ...................................................................................................... 60
U

IEEE Standard for Floating Point ..................................................................................... 61


na

AL
Decimal Type.................................................................................................................... 62
ut

Decimal Literals................................................................................................................ 63
Character Type.................................................................................................................. 64
ho

Character Literals.............................................................................................................. 65
riz

string ................................................................................................................................. 66
U
ed

Escape Characters ............................................................................................................. 67


Boolean Type.................................................................................................................... 68
R

AT
Implicit Conversions......................................................................................................... 69
ep

Explicit Conversions......................................................................................................... 70
Conversions Example ....................................................................................................... 71
ro

Nullable Types.................................................................................................................. 72
d

Lab 3 ................................................................................................................................. 73
uc

IO
Summary ........................................................................................................................... 74
tio

Chapter 4 Operators and Expressions............................................................................ 77


n

Operator Cardinality ......................................................................................................... 79


or

N
Arithmetic Operators ........................................................................................................ 80
Multiplication ................................................................................................................... 81
D
is

Division............................................................................................................................. 82
tri

Additive Operators............................................................................................................ 83
C
bu

Increment and Decrement................................................................................................. 84


Example: A Small Calculator .......................................................................................... 85
tio

Relational Operators ......................................................................................................... 86


O
n

Conditional Logical Operators ......................................................................................... 87


Pr

Short-Circuit Evaluation................................................................................................... 88
Ternary Conditional Operator........................................................................................... 90
PY
oh

Bitwise Operators ............................................................................................................. 91


i

Bitwise Logical Operators ................................................................................................ 92


bi

Bitwise Shift Operators..................................................................................................... 93


te

Assignment Operators....................................................................................................... 94
d

Expressions ....................................................................................................................... 95
Precedence ........................................................................................................................ 96
Associativity ..................................................................................................................... 97
Checking ........................................................................................................................... 98
Lab 4 ................................................................................................................................. 99
Summary ......................................................................................................................... 100

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC vi


All Rights Reserved
Chapter 5 Control Structures........................................................................................ 103
If Test.............................................................................................................................. 105
Blocks ............................................................................................................................. 106
Loops .............................................................................................................................. 107
while Loop ...................................................................................................................... 108
EV
do/while Loops ............................................................................................................... 109
for Loops......................................................................................................................... 110
ForUp Example............................................................................................................... 111
ForDown Example .......................................................................................................... 112
U

Arrays.............................................................................................................................. 113
na

AL
Fibonacci Example ......................................................................................................... 114
ut

foreach Loop ................................................................................................................... 115


break................................................................................................................................ 116
ho

continue........................................................................................................................... 117
riz

goto ................................................................................................................................. 118


U
ed

Structured Programming................................................................................................. 119


Structured Search Example............................................................................................. 120
R

AT
Multiple Methods............................................................................................................ 121
ep

switch .............................................................................................................................. 123


switch in C# and C/C++ ................................................................................................. 124
ro

Lab 5 ............................................................................................................................... 125


d

Summary ......................................................................................................................... 126


uc

IO
tio

Chapter 6 Object-Oriented Programming ................................................................... 129


Objects ............................................................................................................................ 131
n

Objects in the Real World............................................................................................... 132


or

N
Object Models................................................................................................................. 133
Reusable Software Components ..................................................................................... 134
D
is

Objects in Software......................................................................................................... 135


tri

State and Behavior .......................................................................................................... 136


C
bu

Abstraction...................................................................................................................... 137
Encapsulation.................................................................................................................. 138
tio

Classes ............................................................................................................................ 139


O
n

Inheritance Concept ........................................................................................................ 140


Pr

Inheritance Example ....................................................................................................... 141


Relationships among Classes.......................................................................................... 142
PY
oh

Polymorphism................................................................................................................. 143
i

Object Oriented Analysis and Design............................................................................. 145


bi

Use Cases........................................................................................................................ 146


te

CRC Cards and UML ..................................................................................................... 147


d

Summary ......................................................................................................................... 148


Chapter 7 Classes............................................................................................................ 149
Classes as Structured Data.............................................................................................. 151
Classes and Objects ........................................................................................................ 152
References....................................................................................................................... 153

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC vii


All Rights Reserved
Instantiating and Using an Object................................................................................... 154
Assigning Object References.......................................................................................... 155
Garbage Collection ......................................................................................................... 156
Sample Program.............................................................................................................. 157
Methods .......................................................................................................................... 158
EV
Method Syntax Example................................................................................................. 159
Public and Private ........................................................................................................... 160
Abstraction...................................................................................................................... 162
Encapsulation.................................................................................................................. 163
U

Initialization.................................................................................................................... 164
na

AL
Initialization with Constructors ...................................................................................... 165
ut

Default Constructor......................................................................................................... 167


this................................................................................................................................... 168
ho

TestAccount Sample Program ........................................................................................ 169


riz

Static Fields and Methods............................................................................................... 171


U
ed

Static Methods ................................................................................................................ 172


Sample Program.............................................................................................................. 173
R

AT
Static Constructor ........................................................................................................... 174
ep

Constant and Readonly Fields ........................................................................................ 175


Lab 7 ............................................................................................................................... 176
ro

Summary ......................................................................................................................... 177


d uc

Chapter 8 More about Types......................................................................................... 181


IO
tio

Overview of Types in C#................................................................................................ 183


Structures ........................................................................................................................ 184
n

Uninitialized Variables ................................................................................................... 185


or

N
Test Program................................................................................................................... 186
Copying a Structure ........................................................................................................ 187
D
is

Hotel.cs ........................................................................................................................... 188


tri

HotelCopy.cs................................................................................................................... 189
C
Results of Hotel Copy..................................................................................................... 190
bu

Classes and Structs ......................................................................................................... 191


tio

Enumeration Types ......................................................................................................... 192


O
n

Enumeration Types Examples ........................................................................................ 193


Pr

Reference Types ............................................................................................................. 194


Class Types ..................................................................................................................... 195
PY
oh

object............................................................................................................................... 196
i

string ............................................................................................................................... 197


bi

Arrays.............................................................................................................................. 198
te

Default Values ................................................................................................................ 199


d

Boxing and Unboxing..................................................................................................... 201


Implicitly Typed Variables ............................................................................................. 202
Implicitly Typed Variables – Example........................................................................... 203
Lab 8 ............................................................................................................................... 204
Summary ......................................................................................................................... 205

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC viii


All Rights Reserved
Chapter 9 Methods, Properties, and Operators .......................................................... 207
Static and Instance Methods ........................................................................................... 209
Method Parameters ......................................................................................................... 210
No “Freestanding” Functions in C#................................................................................ 211
Classes with All Static Methods ..................................................................................... 212
EV
Parameter Passing ........................................................................................................... 213
Parameter Terminology .................................................................................................. 214
Value Parameters ............................................................................................................ 215
Reference Parameters ..................................................................................................... 216
U

Output Parameters........................................................................................................... 219


na

AL
Structure Parameters ....................................................................................................... 220
ut

Class Parameters ............................................................................................................. 221


Method Overloading ....................................................................................................... 222
ho

Lab 9A ............................................................................................................................ 224


riz

Modifiers as Part of the Signature .................................................................................. 225


U
ed

Variable Length Parameter Lists .................................................................................... 226


Properties ........................................................................................................................ 227
R

AT
Properties Examples ....................................................................................................... 228
ep

Auto-Implemented Properties......................................................................................... 231


Auto-Implemented Property Example ............................................................................ 232
ro

Lab 9B............................................................................................................................. 233


d

Operator Overloading ..................................................................................................... 234


uc

IO
Sample Program.............................................................................................................. 237
tio

Operator Overloading in the Class Library .................................................................... 238


n

Summary ......................................................................................................................... 239


or

N
Chapter 10 Characters and Strings .............................................................................. 243
Characters ....................................................................................................................... 245
D
is

Sample Program.............................................................................................................. 246


tri

Character Codes.............................................................................................................. 247


C
bu

ASCII and Unicode......................................................................................................... 248


Escape Sequences ........................................................................................................... 249
tio

Strings ............................................................................................................................. 250


O
n

String Class ..................................................................................................................... 251


Pr

String Literals and Initialization ..................................................................................... 252


Concatenation ................................................................................................................. 253
PY
oh

Index ............................................................................................................................... 254


i

Relational Operators ....................................................................................................... 255


bi

String Equality ................................................................................................................ 256


te

String Comparisons......................................................................................................... 257


d

String Comparison .......................................................................................................... 258


String Input ..................................................................................................................... 260
String Methods and Properties........................................................................................ 261
StringBuilder Class ......................................................................................................... 263
StringBuilder Equality .................................................................................................... 265
Command Line Arguments............................................................................................. 266

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC ix


All Rights Reserved
Command Line Arguments in the IDE ........................................................................... 267
Command Loops............................................................................................................. 268
Splitting a String ............................................................................................................. 269
Lab 10 ............................................................................................................................. 270
Summary ......................................................................................................................... 271
EV
Chapter 11 Arrays and Indexers................................................................................... 275
Arrays.............................................................................................................................. 277
One Dimensional Arrays ................................................................................................ 278
System.Array .................................................................................................................. 279
U

Sample Program.............................................................................................................. 280


na

AL
Random Number Generation .......................................................................................... 281
ut

Next Methods.................................................................................................................. 282


ho

Jagged Arrays ................................................................................................................. 283


Rectangular Arrays ......................................................................................................... 284
riz

U
Arrays as Collections ...................................................................................................... 285
ed

Bank Case Study: Step 1................................................................................................. 287


Account Class ................................................................................................................. 289
R

AT
Bank Class ...................................................................................................................... 292
ep

TestBank Class ............................................................................................................... 295


ro

Atm Class........................................................................................................................ 297


d

Running the Case Study.................................................................................................. 299


uc

Indexers........................................................................................................................... 301
IO
tio

ColorIndex Example Program ........................................................................................ 303


Using the Indexer............................................................................................................ 304
n

Lab 11 ............................................................................................................................. 305


or

N
Summary ......................................................................................................................... 306
D

Chapter 12 Inheritance .................................................................................................. 309


is

Inheritance Fundamentals ............................................................................................... 311


tri

Inheritance in C#............................................................................................................. 312


C
bu

Single Inheritance ........................................................................................................... 313


Root Class – Object ........................................................................................................ 314
tio

O
Access Control................................................................................................................ 315
n

Public Class Accessibility............................................................................................... 316


Pr

Internal Class Accessibility ............................................................................................ 317


PY
oh

Member Accessibility ..................................................................................................... 318


Member Accessibility Qualifiers .................................................................................... 319
i bi

Member Accessibility Example...................................................................................... 320


te

Method Hiding................................................................................................................ 321


d

Method Hiding and Overriding ...................................................................................... 322


Example: Method Hiding................................................................................................ 323
Initialization.................................................................................................................... 324
Initialization Fundamentals ............................................................................................ 325
Initialization Fundamentals Example ............................................................................. 326
Default Constructor......................................................................................................... 327

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC x


All Rights Reserved
Overloaded Constructors ................................................................................................ 328
Example: Overloaded Constructors ................................................................................ 329
Invoking Base Class Constructors .................................................................................. 330
Base Class Initialization Example .................................................................................. 331
Bank Case Study: Step 2................................................................................................. 332
EV
Bank Case Study Analysis.............................................................................................. 333
Account........................................................................................................................... 334
CheckingAccount............................................................................................................ 335
SavingsAccount .............................................................................................................. 337
U

TestAccount .................................................................................................................... 339


na

AL
Running the Case Study.................................................................................................. 340
ut

Lab 12 ............................................................................................................................. 341


Summary ......................................................................................................................... 342
ho

Chapter 13 Virtual Methods and Polymorphism ........................................................ 345


riz

U
Introduction to Polymorphism ........................................................................................ 347
ed

Abstract and Sealed Classes ........................................................................................... 348


Virtual Methods and Dynamic Binding.......................................................................... 349
R

AT
Type Conversions in Inheritance .................................................................................... 350
ep

Converting Down the Hierarchy..................................................................................... 351


ro

Converting Up the Hierarchy.......................................................................................... 352


d

Virtual Methods .............................................................................................................. 353


uc

Virtual Method Example ................................................................................................ 354


IO
tio

Virtual Method Cost ....................................................................................................... 355


Method Overriding ......................................................................................................... 356
n

The Fragile Base Class Problem..................................................................................... 357


or

N
override Keyword ........................................................................................................... 358
Polymorphism................................................................................................................. 359
D
is

Polymorphism Using “Type Tags”................................................................................. 360


tri

Polymorphism Using Virtual .......................................................................................... 361


C
Polymorphism Example.................................................................................................. 362
bu

Abstract Classes.............................................................................................................. 366


tio

Keyword: abstract .......................................................................................................... 367


O
n

Sealed Classes................................................................................................................. 368


Pr

Heterogeneous Collections ............................................................................................. 369


Heterogeneous Collections Example .............................................................................. 370
PY
oh

Bank Case Study: Step 3................................................................................................. 371


i

Case Study Classes ......................................................................................................... 372


bi

Run the Case Study......................................................................................................... 374


te

Account........................................................................................................................... 375
d

CheckingAccount, SavingsAccount ............................................................................... 376


Bank and Atm ................................................................................................................. 377
TestBank ......................................................................................................................... 378
Lab 13 ............................................................................................................................. 379
Summary ......................................................................................................................... 380

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC xi


All Rights Reserved
Chapter 14 Formatting and Conversion....................................................................... 383
Introduction to Formatting.............................................................................................. 385
ToString .......................................................................................................................... 386
ToString in Your Own Class .......................................................................................... 387
Using Placeholders ......................................................................................................... 389
EV
Format Strings................................................................................................................. 390
Simple Placeholders........................................................................................................ 391
Controlling Width ........................................................................................................... 392
Format String .................................................................................................................. 393
U

Currency.......................................................................................................................... 394
na

AL
Currency Format Example.............................................................................................. 395
ut

String.Format .................................................................................................................. 396


PadLeft and PadRight ..................................................................................................... 397
ho

Bank Case Study: Step 4................................................................................................. 399


riz

Type Conversions ........................................................................................................... 400


U
ed

Conversion of Built-In Types ......................................................................................... 401


Conversion of User-Defined Types ................................................................................ 402
R

AT
User Defined Conversions: Example.............................................................................. 404
ep

Lab 14 ............................................................................................................................. 406


Summary ......................................................................................................................... 407
ro
d

Chapter 15 Exceptions.................................................................................................... 409


uc

Introduction to Exceptions.............................................................................................. 411


IO
tio

Exception Fundamentals................................................................................................. 412


.NET Exception Handling............................................................................................... 413
n

Exception Flow of Control ............................................................................................. 414


or

N
Context and Stack Unwinding ........................................................................................ 415
Exception Example ......................................................................................................... 416
D
is

System.Exception ........................................................................................................... 419


tri

User-Defined Exception Classes .................................................................................... 420


C
bu

User Exception Example ................................................................................................ 421


Structured Exception Handling....................................................................................... 424
tio

Finally Block................................................................................................................... 425


O
n

Bank Case Study: Step 5................................................................................................. 427


Pr

Inner Exceptions ............................................................................................................. 428


Checked Integer Arithmetic............................................................................................ 429
PY
oh

Example Program ........................................................................................................... 430


i

Lab 15 ............................................................................................................................. 431


bi

Summary ......................................................................................................................... 432


te
d

Chapter 16 Interfaces ..................................................................................................... 435


Introduction..................................................................................................................... 437
Interfaces in C#............................................................................................................... 439
Interface Inheritance ....................................................................................................... 440
Programming with Interfaces.......................................................................................... 441
Implementing Interfaces ................................................................................................. 442

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC xii


All Rights Reserved
Using an Interface........................................................................................................... 444
Demo: SmallInterface .................................................................................................... 445
Dynamic Use of Interfaces ............................................................................................. 446
Demo: TryInterfaces ...................................................................................................... 447
is Operator....................................................................................................................... 448
EV
as Operator...................................................................................................................... 449
Bank Case Study: Step 6................................................................................................. 450
Common Interfaces in Case Study –IAccount................................................................ 451
Apparent Redundancy..................................................................................................... 452
U

IStatement ....................................................................................................................... 453


na

AL
IStatement Methods ........................................................................................................ 454
ut

IChecking........................................................................................................................ 455
ISavings .......................................................................................................................... 456
ho

The Implementation........................................................................................................ 457


riz

SavingsAccount .............................................................................................................. 458


U
ed

The Client ....................................................................................................................... 459


Resolving Ambiguity...................................................................................................... 461
R

AT
Access Modifier.............................................................................................................. 462
ep

Explicit Interfaces Test Program .................................................................................... 463


Summary ......................................................................................................................... 464
ro
d

Chapter 17 .NET Interfaces and Collections................................................................ 465


uc

Overview......................................................................................................................... 467
IO
tio

Collections ...................................................................................................................... 468


ArrayList Example.......................................................................................................... 469
n

Count and Capacity......................................................................................................... 470


or

N
foreach Loop ................................................................................................................... 471
Array Notation ................................................................................................................ 472
D
is

Adding to the List ........................................................................................................... 473


tri

Remove Method.............................................................................................................. 474


C
RemoveAt Method.......................................................................................................... 475
bu

Collection Interfaces ....................................................................................................... 476


tio

IEnumerable and IEnumerator........................................................................................ 477


O
n

IEnumerable and IEnumerator Demo: AccountList........................................................ 478


Pr

ICollection ...................................................................................................................... 479


IList................................................................................................................................. 480
PY
oh

A Collection of User-Defined Objects............................................................................ 481


i

Duplicate Objects............................................................................................................ 482


bi

A Correction to AccountList (Step 1)............................................................................. 483


te

Bank Case Study: Step 7................................................................................................. 484


d

Copy Semantics and ICloneable ..................................................................................... 485


Copy Semantics in C#..................................................................................................... 486
Shallow Copy and Deep Copy........................................................................................ 487
Example Program ........................................................................................................... 488
Reference Copy............................................................................................................... 489
Memberwise Clone ......................................................................................................... 490

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC xiii


All Rights Reserved
Using ICloneable ............................................................................................................ 491
Comparing Objects ......................................................................................................... 492
Sorting an Array.............................................................................................................. 493
Anatomy of Array.Sort ................................................................................................... 494
Using the is Operator ...................................................................................................... 495
EV
The Use of Dynamic Type Checking ............................................................................. 496
Implementing IComparable ............................................................................................ 497
Running the Program ...................................................................................................... 498
Complete Solution .......................................................................................................... 499
U

Lab 17A .......................................................................................................................... 500


na

AL
Writing Generic Code..................................................................................................... 501
ut

Using a Class of object ................................................................................................... 502


Generic Types ................................................................................................................. 503
ho

Generic Syntax in C#...................................................................................................... 504


riz

Generic Example............................................................................................................. 505


U
ed

Generic Client Code........................................................................................................ 506


System.Collections.Generic............................................................................................ 507
R

AT
Lab 17B........................................................................................................................... 508
ep

Object Initializers............................................................................................................ 509


Collection Initializers...................................................................................................... 510
ro

Anonymous Types .......................................................................................................... 511


d

Summary ......................................................................................................................... 512


uc

IO
tio

Chapter 18 Delegates and Events .................................................................................. 517


Overview of Delegates and Events................................................................................. 519
n

Callbacks and Delegates ................................................................................................. 520


or

N
Usage of Delegates ......................................................................................................... 521
Declaring a Delegate....................................................................................................... 522
D
is

Defining a Method .......................................................................................................... 523


tri

Creating a Delegate Object ............................................................................................. 524


C
Calling a Delegate........................................................................................................... 525
bu

A Random Array............................................................................................................. 526


tio

Anonymous Methods...................................................................................................... 527


O
n

Combining Delegate Objects .......................................................................................... 528


Pr

Account.cs....................................................................................................................... 529
DelegateAccount.cs ........................................................................................................ 530
PY
oh

Lambda Expressions ....................................................................................................... 531


i

Named Method ............................................................................................................... 532


bi

Anonymous Method ....................................................................................................... 533


te

Lambda Expression Example ......................................................................................... 534


d

Events.............................................................................................................................. 535
Events in C# and .NET ................................................................................................... 536
Client Side Event Code................................................................................................... 538
Chat Room Example ....................................................................................................... 539
Lab 18 ............................................................................................................................. 540
Summary ......................................................................................................................... 541

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC xiv


All Rights Reserved
Chapter 19 Introduction to Windows Forms ............................................................. 543
Creating a Windows Forms App .................................................................................... 545
Partial Classes ................................................................................................................. 550
Windows Forms Event Handling.................................................................................... 551
Add Events for a Control ................................................................................................ 552
EV
Events Documentation.................................................................................................... 553
Closing a Form................................................................................................................ 554
ListBox Control .............................................................................................................. 555
ListBox Example ............................................................................................................ 556
U

Lab 19 ............................................................................................................................. 557


na

AL
Summary ......................................................................................................................... 558
ut

Chapter 20 Newer Features in C# ............................................................................... 563


ho

dynamic Type.................................................................................................................. 565


Runtime Error Example .................................................................................................. 566
riz

U
dynamic versus object..................................................................................................... 567
ed

Behavior of object........................................................................................................... 568


Behavior of dynamic....................................................................................................... 569
R

AT
Named Arguments .......................................................................................................... 570
ep

Optional Arguments........................................................................................................ 571


ro

Book Class ...................................................................................................................... 572


d

Using Optional Arguments ............................................................................................. 573


uc

Variance in Generic Interfaces ....................................................................................... 574


IO
tio

Covariance Example ....................................................................................................... 575


Variance with IComparer<T>......................................................................................... 576
n

Interfaces with Variance Support ................................................................................... 577


or

N
Contravariance Example................................................................................................. 578
Asynchronous Programs in C# 5.0 ................................................................................. 579
D
is

Task and Task<TResult>................................................................................................ 580


tri

Aysnc Methods ............................................................................................................... 581


C
bu

Async Example ............................................................................................................... 582


Synchronous Call............................................................................................................ 583
tio

Async Call....................................................................................................................... 584


O
n

Threading ........................................................................................................................ 585


Pr

New Features in C# 6.0................................................................................................... 586


Null-Conditional Operator.............................................................................................. 587
PY
oh

Composite Format String................................................................................................ 588


i

Interpolated Strings......................................................................................................... 589


bi

New Features in C# 7.0................................................................................................... 590


te

Tuples.............................................................................................................................. 591
d

Nullable Reference Types............................................................................................... 592


Nullable Reference Example Program ........................................................................... 593
Summary ......................................................................................................................... 594
Appendix A Learning Resources .............................................................................. 595

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC xv


All Rights Reserved
EV
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright ©2019 Object Innovations Enterprises, LLC xvi


All Rights Reserved
CSharp Chapter 1
EV
Chapter 1
U
na

AL
ut
ho

Introduction to .NET
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 1


All Rights Reserved
CSharp Chapter 1

Introduction to .NET

Objectives
EV
After completing this unit you will be able to:
U

 Give a high-level overview of .NET.


na

AL
ut

 Outline the architectural components of .NET.


ho
riz

 Describe the essentials of creating and running a


U
ed

program in the .NET environment.


R

AT
ep

 Build and run a simple C# program.


ro
d

 Use Visual Studio 2019 as an effective environment


uc

IO
for creating C# programs.
tio
n

 Use the .NET documentation.


or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 2


All Rights Reserved
CSharp Chapter 1

What Is .NET?

 .NET is Microsoft's software platform for building


EV
applications for many environments.
 Originally proprietary and restricted to Microsoft Windows,
U

.NET is now open source and cross-platform.


na

AL
ut

 .NET applications can be built using multiple


ho

languages.
riz

U
ed

 C# and Visual Basic are object-oriented languages.


R

AT
 F# is a functional language which also supports object-
ep
ro

oriented and imperative programming.


d uc

 .NET Standard is a base set of APIs common to all


IO
tio

.NET platforms.
n
or

 There are multiple implementations of .NET


N
D

supporting.NET Standard. Each implementation can


is
tri

support additional APIs specific to the OS on which it


C
bu

runs.
tio

O
 .NET Framework is the original implementation of .NET
n
Pr

supporting server and desktop applications on Windows. As


PY
oh

of version 4.5 it supports .NET Standard.


i bi

 .NET Core is designed for server and cloud applications. It


te

runs on Windows, macOS and Linux.


d

 Xamarin/Mono supports apps running on mobile devices.


 Universal Windows Platform (UWP) supports touch-enabled
apps running on various Windows platforms.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 3


All Rights Reserved
CSharp Chapter 1

Libraries and Tools

 Microsoft and third parties provide many libraries to


EV
extend .NET.
 Many libraries are furnished through NuGet packages.
U
na

AL
 NuGet is a package manager specifically designed for .NET.
ut
ho

 Microsoft and third parties provide many libraries to


riz

extend .NET.
U
ed

 Visual Studio is a full-featured IDE running on


R

AT
ep

Windows for building all types of .NET applications.


ro

 Visual Studio for Mac runs on Mac computers.


d uc

IO
tio

 It can be used for building iOS and macOS apps as well as


n

Android and Windows apps with Xamarin.


or

N
 It can also be used for ASP.NET Core apps and services.
D
is
tri

 Visual Studio Code is a lightweight code editor


C
bu

available for Windows, macOS and Linux.


tio

O
 It comes with built in support for JavaScript and extensions
n
Pr

for many languages, including C#, C++, Java, Python, PHP,


PY
oh

and others.
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 4


All Rights Reserved
CSharp Chapter 1

Application Models

 Web applications and services


EV
 ASP.NET supports web applications on Windows
 ASP.NET Core is cross-platform, targeting Windows,
U
na

AL
macOS and Linux
ut
ho

 Mobile applications
riz

U
 Cross-platform targeting iOS, Android and Windows
ed
R

 Desktop
AT
ep
ro

 Windows desktop applications using Windows Forms or


d

Windows Presentation Foundation (WPF).


uc

IO
tio

 Mac desktop applications


n
or

 Microservices -- a design pattern in which apps are


N
D

composed of small, independent modules.


is
tri

 Docker containers combine microservices into single


C
bu

deployable units.
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 5


All Rights Reserved
CSharp Chapter 1

Managed Code

 Compilers for .NET languages generate common


EV
intermediate language (CIL).
 A CIL program does not run directly on hardware
U
na

but on a virtual machine, called a runtime.


AL
ut

 .NET runtimes include:


ho
riz

 Common Language Runtime (CLR) for .NET Framework.


U
ed

 Core Common Language Runtime (CoreCLR) for .NET


R

AT
ep

Core.
ro

 Mono runtime for Xamarin iOS and Android and Mono


d uc

IO
desktop.
tio

 .NET Native for UWP.


n
or

N
 A runtime provides various services such as
D
is

automatic memory management, type safety, and so


tri

C
on.
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 6


All Rights Reserved
CSharp Chapter 1

.NET Programming in a Nutshell

1. Write your program in a high-level .NET language, such as C#.


EV
2. Compile your program into CIL.
3. Run your CIL program, which will launch a runtime such as
U
na

CLR or CoreCLR to execute your CIL, using its just-in-time


AL
ut

compiler to translate your program to native code as it executes.


ho

 In this course we will use the .NET Framework.


riz

U
ed

 Programs will compile into .EXE files that will run in the
R

AT
CLR.
ep

 We will look at a simple example of a C# program,


ro
d

and run it under .NET.


uc

IO
tio

// SimpleCalc.cs
n

//
or

N
// This program does a simple calculation:
D

// calculate area of a rectangle


is
tri

using System;
C
bu
tio

public class SimpleCalc


O
{
n

static void Main()


Pr

{
PY
oh

int width = 20;


i bi

int height = 5;
te

int area;
d

area = width * height;


Console.WriteLine("area = {0}", area);
}
}

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 7


All Rights Reserved
CSharp Chapter 1

Visual Studio 2019

 While it is possible to write C# programs using any


EV
text editor, and compile them with the command-line
compiler, it is very tedious to program that way.
U

 An IDE makes the process of writing software much


na

AL
ut

easier.
ho

 An IDE provides convenience items, such as a syntax-


riz

U
highlighting editor.
ed

 An IDE reduces the tedium of keeping track of


R

AT
ep

configurations, environment settings and file organizations.


ro

 You may use Visual Studio 2019 throughout this


d uc

IO
course to create and compile your C# programs.
tio
n

 Visual Studio 2019 is discussed in more detail in


or

N
Appendix A.
D
is

 In this course you may use any version of VS 2019,


tri

C
bu

including the free Visual Studio 2019 Community.


tio

O
 Although it is easy to create and run .NET Core
n
Pr

programs using Visual Studio, in this course we will


PY
oh

use .NET Framework.


i bi

 We are using .NET Framework 4.7.2, which supports .NET


te
d

Standard, and comes bundled with Visual Studio 2019.


 Hence our programs will run on any .NET implementation,
including .NET Core.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 8


All Rights Reserved
CSharp Chapter 1

Visual Studio Sign In

 When you first bring up Visual Studio on a new


EV
device, you will be invited to sign in.
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

 Sign in with any Microsoft ID.


 By doing so you will synchronize your settings among
devices and connect to online developer services.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 9


All Rights Reserved
CSharp Chapter 1

Creating a Console Application

 We will now create a simple console application using


EV
Visual Studio.
 Our program is the simple calculator whose code we showed
U

earlier.
na

AL
ut

1. From the Visual Studio start page click on "Create a new


ho

project". This will bring up the New Project dialog. (You can
riz

also use the menu File | New | Project when the main Visual
U
ed

Studio window is open.)


R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 10


All Rights Reserved
CSharp Chapter 1

Creating a Console App (Cont'd)

2. Choose Console App (.NET Framework) with language C#.


EV
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
3. Click Next.
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 11


All Rights Reserved
CSharp Chapter 1

Configure Your New Project

4. In the Project name field, type SimpleCalcVs and for Location


EV
browse to C:\OIC\CSharp\Demos. Leave Solution name as
SimpleCalcVs. Leave unchecked "Place solution and project in
the same directory." 1 For Framework select .NET Framework
U

4.7.2.
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

5. Click Create.
PY
oh
i bi
te
d

1
Examples in later chapters may place project and solution in the same directory.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 12


All Rights Reserved
CSharp Chapter 1

Program.cs Starter Code

 There will be a number of starter files. The key file is


EV
Program.cs, which will be shown, ready to edit.
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 13


All Rights Reserved
CSharp Chapter 1

Using the Visual Studio Text Editor

 The file Program.cs will be open in the Visual Studio


EV
text editor. Replace the starter code with the
highlighted code shown below:
U

using System;
na

AL
using System.Collections.Generic;
ut

using System.Linq;
ho

using System.Text;
riz

using System.Threading.Tasks;
U
ed

public class SimpleCalc


R

AT
{
ep

static void Main()


ro

{
d

int width = 20;


uc

IO
int height = 5;
tio

int area;
n

area = width * height;


or

Console.WriteLine("area = {0}", area);


N
D

}
is

}
tri

C
bu

 Notice that the starter code provided several using


tio

statements. The only one that is needed is for the System


O
n

namespace.
Pr

PY
 Unneeded ones can be removed by right-clicking over the
oh
i

using area and selecting Remove ... from the context menu.
bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 14


All Rights Reserved
CSharp Chapter 1

IntelliSense

 A powerful feature of Visual Studio is IntelliSense.


EV
 IntelliSense will automatically pop up a list box allowing you
to easily insert language elements directly into your code.
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D

 For now, don’t actually add another WriteLine() statement.


is
tri

We’ll see the effect of the extra statement shortly.


C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 15


All Rights Reserved
CSharp Chapter 1

Build the Project

 Building a project means compiling the individual


EV
source files and linking them together with any
library files to create an IL executable .EXE file.
U

 To make it easier to build, add the Build toolbar (if it


na

AL
ut

is not already present) by a right-click over the


ho

toolbar area. Check Build.


riz

U
ed
R

AT
ep
ro
d

 Then you can build the project by using one of the


uc

IO
following:
tio
n

 Menu Build | Build Solution or toolbar button or


or

N
keyboard shortcut Ctrl+Shift+B.
D
is

 Menu Build | Build SimpleCalcVs or toolbar button (this


tri

C
just builds the project SimpleCalcVs)2.
bu
tio

O
n
Pr

PY
oh
i bi
te
d

2
The two are the same in this case, because the solution has only one project, but some solutions have
multiple projects, and then there is a difference.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 16


All Rights Reserved
CSharp Chapter 1

Run the Project

 You can run the program without the debugger by


EV
using one of the following:
 Menu Debug | Start Without Debugging
U
na

AL
 Toolbar button (This button is not provided by default;
ut

see Appendix A for how to add it to your Build toolbar.)


ho
riz

 Keyboard shortcut Ctrl + F5


U
ed

 You can run the program in the debugger by using


R

AT
ep

one of the following:


ro

 Menu Debug | Start Debugging


d uc

IO
 Toolbar button
tio
n

 Keyboard shortcut F5.


or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 17


All Rights Reserved
CSharp Chapter 1

Pausing the Output

 If you run the program in the debugger from Visual


EV
Studio, you will notice that the output window
automatically closes on program termination.
U

 To keep the window open, you may prompt the user


na

AL
ut

for some input.


ho

public class SimpleCalc


riz

U
{
ed

static void Main()


R

{
AT
ep

int width = 20;


int height = 5;
ro

int area;
d uc

area = width * height;


IO
tio

Console.WriteLine("area = {0}", area);


Console.WriteLine("Prese Enter to exit");
n

Console.ReadLine();
or

N
}
D

}
is
tri

C
 This program is saved as a Visual Studio solution in
bu
tio

Chap01\SimpleCalcVs.
O
n

 Remember that you can always make the console


Pr

PY
oh

window stay open by running without the debugger


i

via Ctrl + F5.


bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 18


All Rights Reserved
CSharp Chapter 1

Visual C# and GUI Programs

 Microsoft’s implementation of the C# language,


EV
Visual C#, works very effectively in a GUI
environment.
U

 Using Windows Forms (available in .NET Framework but


na

AL
not .NET Core), it is easy to create Windows GUI programs
ut
ho

in C#.
riz

U
Example: See Chap01\SimpleCalcGui
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is

 We will discuss GUI programming using C# in


tri

C
bu

Chapter 19.
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 19


All Rights Reserved
CSharp Chapter 1

.NET Documentation

 .NET Framework documentation is available online.


EV
 It is now part of comprehensive Microsoft
documentation at
U
na

AL
https://docs.microsoft.com
ut
ho

 Select .NET.
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 20


All Rights Reserved
CSharp Chapter 1

Summary

 .NET is Microsoft's software platform for building


EV
applications for many environments.
 .NET applications can be built using multiple
U
na

languages, including C#.


AL
ut

 C# is an object-oriented language designed by Microsoft for


ho

.NET.
riz

U
ed

 .NET Standard is a base set of APIs common to all


R

AT
.NET platforms.
ep
ro

 There are multiple implementations of .NET


d

supporting .NET Standard, including the classical


uc

IO
tio

.NET Framework and the newer .NET Core.


n

 Visual Studio is a full-featured IDE running on


or

N
Windows for building all types of .NET applications.
D
is
tri

 With Visual Studio it is easy to create and run


C
bu

programs using C#.


tio

O
n

 You can access extensive .NET Framework


Pr

documentation online.
PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 21


All Rights Reserved
CSharp Chapter 1
EV
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 22


All Rights Reserved
CSharp Chapter 2
EV
Chapter 2
U
na

AL
ut
ho

First C# Programs
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 23


All Rights Reserved
CSharp Chapter 2

First C# Programs

Objectives
EV
After completing this unit you will be able to:
U

 Write a basic “Hello, World” program in C#.


na

AL
ut

 Compile and run C# programs in your local


ho

development environment.
riz

U
ed

 Describe the basic structure of C# programs.


R

AT
ep

 Describe how related C# classes can be grouped into


ro

namespaces.
d uc

IO
 Use variables and simple expressions in C# programs.
tio
n

 Write C# programs that can perform simple


or

N
calculations.
D
is

 Perform simple input and output in C#.


tri

C
bu

 Describe objects and classes in C#.


tio

O
n

 Use an input wrapper class to perform input in C#.


Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 24


All Rights Reserved
CSharp Chapter 2

Hello, World

 Whenever learning a new programming language, a


EV
good first step is to write and run a simple program
that will display a single line of text.
U

 Such a program demonstrates the basic structure of the


na

AL
language, including output.
ut
ho

 You must learn the pragmatics of compiling and running the


riz

U
program.
ed

 Here is “Hello, World” in C#:


R

AT
ep

 See Demos\Hello\Hello.cs, backed up in Chap02\Hello.


ro
d uc

// Hello.cs
IO
tio

class Hello
n

{
or

N
public static int Main(string[] args)
D

{
is

System.Console.WriteLine(
tri

C
"Hello, World");
bu

return 0;
tio

}
O
n

}
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 25


All Rights Reserved
CSharp Chapter 2

Program Structure
// Hello.cs
EV
class Hello
{
U

...
na

}
AL
ut

 Every C# program has at least one class.


ho
riz

 A class is the foundation of C#’s support for object-oriented


U
ed

programming.
R

AT
ep

 A class encapsulates data (represented by variables) and


ro

behavior (represented by methods).


d uc

 All of the code defining the class (its variables and methods)
IO
tio

will be contained between the curly braces.


n
or

 We will discuss classes in detail later.


N
D

 Note the comment at the beginning of the program.


is
tri

C
bu

 A line beginning with a double slash is present only for


tio

documentation purposes and is ignored by the compiler.


O
n

 C# files have the extension .cs.


Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 26


All Rights Reserved
CSharp Chapter 2

Program Structure (Cont’d)


// Hello.cs
EV
class Hello
{
U

public static int Main(string[] args)


na

{
AL
...
ut

return 0;
ho

}
riz

U
}
ed

 Every C# program has a distinguished class that has


R

AT
ep

a method whose name must be Main.


ro

 Note the capitalization!


d uc

IO
tio

 The method should be public and static.


n

 An int exit code can be returned to the operating system. Use


or

N
void if you do not return an exit code.
D
is
tri

public static void Main(string[] args)


C
bu

 Command line arguments are passed as an array of strings.


tio

O
n

 You may omit the command line arguments.


Pr

PY
oh

public static void Main()


i bi

 The runtime will call this Main method – it is the entry point
te
d

for the program.


 All of the code for the Main method will be between the
curly braces.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 27


All Rights Reserved
CSharp Chapter 2

Program Structure (Cont’d)


// Hello.cs
EV
class Hello
{
U

public static int Main(string[] args)


na

{
AL
System.Console.WriteLine(
ut

"Hello, World");
ho

return 0;
riz

U
}
ed

}
R

AT
 Every method in C# has one or more statements.
ep
ro

 A statement is terminated by a semicolon.


d uc

IO
 A statement may be spread out over several lines.
tio
n

 The Console class provides support for standard


or

N
D

output and standard input.


is
tri

 The method WriteLine displays a string, followed by a new


C
bu

line.
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 28


All Rights Reserved
CSharp Chapter 2

Namespaces

 Much of the standard functionality in C# is provided


EV
through many classes in the .NET Framework.
 Related classes are grouped into namespaces.
U
na

AL
 The fully-qualified name of a class is specified by the
ut
ho

namespace, followed by a dot, followed by the class


riz

name.
U
ed

System.Console
R

AT
ep

 A using statement allows a class to be referred to by


ro

its class name alone.


d uc

IO
// Hello2.cs
tio
n

using System;
or

N
D

class Hello
is

{
tri

public static void Main()


C
bu

{
tio

Console.WriteLine("Hello, World");
O
}
n

}
Pr

PY
oh

 Note that in C# it is not necessary for the file name to


i bi

be the same as the name of the class containing the


te
d

Main method.
 This version of the program also illustrates a Main()
method with no command-line arguments and void
return type.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 29


All Rights Reserved
CSharp Chapter 2

Exercise

 Take a few minutes to add two more lines of code to


EV
your program.
 Print out the phrase “My name is XXXX” (use your own
U

name).
na

AL
ut

 Then print out “Goodbye.”


ho
riz

 Save your file, compile the program, and run it.


U
ed

 Your output should be something like this:


R

AT
ep

Hello, World
ro

My name is Bob
d

Goodbye
uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 30


All Rights Reserved
CSharp Chapter 2

Answer
// Hello3.cs
EV
using System;
U

class Hello
na

{
AL
public static void Main()
ut

{
ho

Console.WriteLine("Hello, World");
riz

U
Console.WriteLine("My name is Bob");
ed

Console.WriteLine("Goodbye");
}
R

AT
ep

}
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 31


All Rights Reserved
CSharp Chapter 2

Variables

 In C#, you can define variables to hold data.


EV
 Variables represent storage locations in memory.
U

 In C#, variables are of a specific data type.


na

AL
ut

 Some common types are int for integers and double for
ho

floating point numbers.


riz

U
 You must declare variables before you can use them.
ed
R

AT
 A variable declaration reserves memory space for the
ep

variable and may optionally specify an initial value.


ro
d uc

int kilo = 1024; // reserves space and assigns


IO
// an intial value
tio

int mega; // reserves space but does


n

// not initialize
or

N
D

 If a variable is not initialized in its declaration, it should be


is

assigned prior to being used.


tri

C
bu

int kilo;
tio

kilo = 1024;
O
n

// Now you may use kilo


Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 32


All Rights Reserved
CSharp Chapter 2

Expressions

 You can combine variables and constants (or


EV
“literals”) via operators to form expressions.
 Examples of operators include the standard
U
na

arithmetic operators:
AL
ut

+ addition
ho

- subtraction
riz

* multiplication
U
ed

/ division
R

AT
 Here are some examples of expressions:
ep
ro

kilo * 1024
d uc

(fahrenheit – 32) * 5 / 9
IO
3.1416 * radius * radius
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 33


All Rights Reserved
CSharp Chapter 2

Assignment

 You can assign a value to a variable by using the =


EV
symbol.
 On the left hand side is a variable.
U
na

AL
 On the right hand side is an expression.
ut
ho

 The expression is evaluated and its value is assigned to the


riz

variable on the left.


U
ed

 Assignment is a statement and must be terminated by a


R

AT
semicolon.
ep
ro

mega = kilo * 1024;


d

celsius = (fahrenheit – 32) * 5 / 9;


uc

IO
area = 3.1416 * radius * radius;
tio
n

 Note that the same variable can be used on both sides


or

N
of an assignment statement.
D
is

int item = 5;
tri

C
int total = 30;
bu

total = total + item;


tio

O
n

 The expression total + item evaluates to 35, using the old


Pr

value of total, and this value is assigned to total, creating a


PY
oh

new value.
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 34


All Rights Reserved
CSharp Chapter 2

Calculations Using C#

 You can easily use C# to perform calculations by


EV
adding code to the Main method of a C# class.
 Declare whatever variables you need.
U
na

AL
 Create expressions and assign values to your variables.
ut
ho

 Print out the answer using Console.WriteLine().


riz

U
 You can easily perform labeled output, relying on two
ed

features of C#:
R

AT
ep

 The operator + performs concatenation for string data.


ro
d

 There is an automatic, implicit conversion available that


uc

IO
converts numeric data to string data when required.
tio
n

 Hence this code ...


or

N
D

int total = 35;


is

System.Console.WriteLine("The total is " + total);


tri

C
bu

 ... will produce this output:


tio

O
n

The total is 35
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 35


All Rights Reserved
CSharp Chapter 2

Sample Program

 This program will convert temperature from


EV
Fahrenheit to Celsius.
 See Convert\Step1.
U
na

AL
// Convert.cs - Step 1
ut

//
ho

// Program converts a hardcoded temperature in


riz

// Fahrenheit to Celsius
U
ed

using System;
R

AT
ep

class Convert
ro

{
d

public static void Main(string[] args)


uc

IO
{
tio

int fahr = 86;


n

int celsius = (fahr - 32) * 5 / 9;


or

Console.WriteLine("fahrenheit = " + fahr);


N
Console.WriteLine("celsius = " + celsius);
D

}
is
tri

}
C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 36


All Rights Reserved
CSharp Chapter 2

More about Output in C#

 The Console class in the System namespace supports


EV
two simple methods for performing output:
 WriteLine() writes out a string followed by a new line.
U
na

AL
 Write() writes out just the string without the new line.
ut
ho

int x = 24;
riz

int y = 5;
U
int z = x * y;
ed

Console.Write("Product of " + x + " and " + y);


R

AT
Console.WriteLine(" is " + z);
ep

Console.WriteLine("The product is {0}", z);


ro

 The output is all on one line:


d uc

IO
tio

Product of 24 and 5 is 120


n

 A more convenient way to build up an output string


or

N
D

is to use placeholders {0}, {1}, etc.


is
tri

 An equivalent way to do the output shown above is:


C
bu
tio

Console.WriteLine("Product of {0} and {1} is {2}",


O
x, y, z);
n
Pr

 The program OutputDemo illustrates the output operations


PY
oh

just discussed.
i bi
te

 Later in the course we will see how to control formatting of


d

output, and occasionally in examples we will throw in some


simple use of formatting.

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 37


All Rights Reserved
CSharp Chapter 2

Input in C#

 Our first Convert program is not too useful, because


EV
the Fahrenheit temperature is hard-coded.
 To convert a different temperature, you would have to edit
U

the source file and recompile.


na

AL
ut

 What we really want to do is allow the user of the


ho

program to enter a value at runtime for the


riz

U
Fahrenheit temperature.
ed

 Although simple console input in C# is fairly easy, we


R

AT
ep

can make it even easier using object-oriented


ro

programming.
d uc

IO
 We can encapsulate or “wrap” the details of input in a class.
tio
n

 It will be easy to use the wrapper class.


or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 38


All Rights Reserved
CSharp Chapter 2

More about Classes

 Although we will discuss classes in more detail later,


EV
there is a little more you need to know now.
 A class can be thought of as a template for creating
U
na

objects.
AL
ut

 An object is an instance of a class.


ho
riz

 A class specifies data and behavior.


U
ed

 The data is different for each object instance.


R

AT
ep

 In C#, you instantiate a class by using the new


ro
d

keyword.
uc

IO
tio

InputWrapper iw = new InputWrapper();


n

 This code creates the object instance iw of the


or

N
D

InputWrapper class.
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 39


All Rights Reserved
CSharp Chapter 2

InputWrapper Class

 The InputWrapper class “wraps” interactive input for


EV
several basic data types.
 The supported data types are int, double, decimal and
U

string.
na

AL
ut

 Methods getInt, getDouble, getDecimal and getString are


ho

provided.
riz

U
 A prompt string is passed as an input parameter.
ed
R

AT
 See files InputWrapper.cs in directory TestInputWrapper,
ep

which implements the class, and TestInputWrapper.cs,


ro

which tests the class.


d uc

IO
 Although the code is quite short, it is a little complex,
tio
n

involving a number of different methods from


or

N
different .NET Framework classes.
D
is

 However, you do not need to be familiar with the


tri

C
implementation of InputWrapper in order to use it.
bu
tio

 That is the beauty of “encapsulation”—complex functionality


O
n

can be hidden by an easy-to-use interface.


Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 40


All Rights Reserved
CSharp Chapter 2

Echo Program

 We illustrate interactive input by a simple “echo”


EV
program.
 The program prompts the user for a name, and then prints out
U

a personalized greeting.
na

AL
ut

 See Echo.
ho
riz

 This directory has two files, each defining a class.


U
ed

 InputWrapper.cs defines the wrapper class. There is no


R

AT
ep

Main method in this class.


ro

 EchoName.cs has a class Echo, with a Main method.


d uc

IO
// EchoName.cs
tio

//
n

// Prompts user to enter name and then


or

N
// prints out greeting using name
D
is

using System;
tri

C
bu

class Echo
tio

{
O
public static void Main(string[] args)
n
Pr

{
PY
InputWrapper iw = new InputWrapper();
oh

string name = iw.getString("Enter your name: ");


i bi

Console.WriteLine("Hello, " + name);


te

}
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 41


All Rights Reserved
CSharp Chapter 2

Using InputWrapper

 The bolded statements illustrate how to use the


EV
InputWrapper class.
 Instantiate an InputWrapper object iw by using new.
U
na

AL
 Prompt to obtain input data by calling the appropriate
ut

getXXX method.
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 42


All Rights Reserved
CSharp Chapter 2

Multiple Files in Visual Studio

 It is very easy to work with Visual Studio projects


EV
that have multiple files.
 As an example, open the Visual Studio solution that is
U
na

specified by the file Chap02\Echo\Echo.sln.


AL
ut

 A solution can contain one or more projects.


ho
riz

 In this case there is a single project file Echo.csproj.


U
ed

 You can see all the files in a solution through the


R

AT
ep

Solution Explorer.
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n

 When you build the solution via the toolbar button ,


Pr

you will build all the projects in the solution.


PY
oh
i

 You can also build just the current project via the toolbar
bi
te

button .
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 43


All Rights Reserved
CSharp Chapter 2

The .NET Framework

 The .NET Framework has a very large class library


EV
(several thousand classes).
 To make all of this functionality more manageable,
U
na

the classes are partitioned into namespaces.


AL
ut

 The root namespace is System, which directly


ho
riz

contains many useful classes, among them:


U
ed

 Console provides access to standard input, output and error


R

AT
streams for I/O.
ep
ro

 Convert provides conversions among base data types.


d uc

 Math provides mathematical constants and functions.


IO
tio

 This courses uses .NET Framework 4.7.2, the latest


n
or

N
released version of the .NET Framework at the time
D

Visual Studio 2019 was released.


is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 44


All Rights Reserved
CSharp Chapter 2

The .NET Framework (Cont’d)

 Underneath System, there are other namespaces,


EV
among them:
 System.Data contains classes constituting the ADO.NET
U

architecture for accessing databases.


na

AL
ut

 System.Xml provides standards-based support for processing


ho

XML.
riz

U
 System.Drawing contains classes providing GDI+ graphics
ed

functionality.
R

AT
ep

 System.Windows.Forms provides support for creating


ro

applications with rich Windows-based interfaces.


d uc

IO
 System.Web provides support for browser/server
tio

communication.
n
or

N
 System.IO provides support for reading and writing with
D

streams and files. Both synchronous and asynchronous I/O


is
tri

are supported.
C
bu

 System.Net provides support for several standard network


tio

O
protocols.
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 45


All Rights Reserved
CSharp Chapter 2

Lab 2

C# Programs for Calculation


EV
In this lab you modify or implement several C# programs to
perform calculations. You need to perform input (through a
U
na

wrapper class), perform a calculation, and output the result. Do as


AL
ut

many of these exercises as time permits. If you have extra time, do


ho

some of the optional experiments suggested in some of the


riz

exercises, or make up some experiments on your own.


U
ed

Detailed instructions are contained in the Lab 2 write-up at the end


R

AT
of the chapter.
ep
ro

Suggested time: 30 minutes


d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 46


All Rights Reserved
CSharp Chapter 2

Summary

 Every C# application has a class with a method Main,


EV
which is the entry point into the application.
 The System class includes methods for performing
U
na

output, such as WriteLine.


AL
ut

 Expressions in C# are formed from literals, variables


ho
riz

and operators.
U
ed

 With the assignment statement, you can assign a


R

AT
value computed by an expression to a variable.
ep
ro

 Input in C# is a little more complicated than output,


d uc

but you can use a wrapper class that encapsulates the


IO
tio

required C# classes and presents a simple


n

programming interface.
or

N
 The .NET Framework has a large class library that is
D
is

partitioned into namespaces.


tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 47


All Rights Reserved
CSharp Chapter 2

Lab 2

C# Programs for Calculation

Introduction
EV
In this lab, you modify or implement several C# programs to perform
calculations. You need to perform input (through a wrapper class), perform a calculation,
U

and output the result. Do as many of these exercises as time permits. If you have extra
na

AL
time, do some of the optional experiments suggested in some of the exercises, or make up
some experiments on your own.
ut
ho

Suggested Time: 30 minutes


riz

U
Root Directory: OIC\CSharp
ed

Directories: Labs\Lab2\Convert (Exercise 1 work)


R

AT
ep

Chap02\Convert\Step1 (Backup of Exercise 1 starter files)


Chap02\Convert\Step2 (Answer to Exercise 1)
ro

Chap02\TestInputWrapper (InputWrapper class)


d

Labs\Lab2 (Exercise 2 work)


uc

IO
Chap02\Circle (Exercise 2 answer)
tio

Exercise 1. Fahrenheit to Celsius Conversion


n
or

N
Examine the code of the starter program. Build and run. Notice that the
D

Fahrenheit temperature to be converted is hard-coded. Modify the program to prompt the


is

user for a Fahrenheit temperature, read in the value entered by the user, and print out the
tri

result. Make use of the wrapper class InputWrapper that was discussed in this chapter.
C
bu

The starter program uses int as the data type for temperatures. An optional
tio

experiment is to use double as the data type. Could you input the Fahrenheit temperature
O
n

as an int and calculate the Celsius temperature as a double?


Pr

PY
Exercise 2. Calculate the Area of a Circle
oh
i

Use Visual Studio to create an empty C# project Circle in the Lab2 folder. This
bi

will create the folder Circle. Add a new file Circle.cs to your project, where you will
te

place your program code.


d

Write a C# program to calculate the area of a circle. Prompt the user for the
radius, read in the value entered by the user, calculate the area of the circle, and print out
the result. For pi, use the approximation 3.1416. What is an appropriate data type to use
for radius and area?

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 48


All Rights Reserved
CSharp Chapter 2

As an optional experiment, use the class Math (in the namespace System) for a
more accurate value of pi.

Another optional experiment is to capture the output data in a file. This is easy to
do at the command line, by using the > to “redirect” output to a file.
EV
Circle > output.txt

When using this technique, the prompts are written to the output file and not displayed on
the screen. Hence you need to know what to type! If you type “10” for the radius, your
U
na

output file should look like:


AL
ut

radius: Using, 3.1416, area = 314.16


ho

Using, Math.PI, area = 314.15926535897933


riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 49


All Rights Reserved
CSharp Chapter 2
EV
U
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
d uc

IO
tio
n
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
i bi
te
d

Rev. 4.8.5 Copyright © 2019 Object Innovations Enterprises, LLC 50


All Rights Reserved
EVU
na

AL
ut
ho
riz

U
ed
R

AT
ep
ro
ucd

IO
7400 E. Orchard Road, Suite 1450 N
tio

Greenwood Village, Colorado 80111


Ph: 303-302-5280
n

www.ITCourseware.com
or

N
D
is
tri

C
bu
tio

O
n
Pr

PY
oh
bii
te
d

9-08-00407-000-04-18-19

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy