Anda di halaman 1dari 0

Contents

C# Programming

C# Programming

C# Programming
For the .NET Framework version 1.0.3705
Courseware Number #10010B

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


1

Contents

Copyright 2002 Third Millennium, LLP, 21 Moon Hill Road, Lexington MA 02421,
USA. All rights reserved.
This product or document is protected by copyright and distributed under license
restricting its use, copying, and distribution. No part of this product or document may be
reproduced in any form by any means without prior written authorization of Third
Millennium, LLP and its licenses, if any.
Microsoft is a registered trademark. Visual C#, Visual Basic, Visual Studio, Windows,
Windows 98, Windows NT, Windows 2000, and Windows XP are either registered
trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries.
Sun, Sun Microsystems, Java are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States and other countries.
Other product and company names herein may be the trademark of their respective
owners.

C# Programming (Courseware #10010B)


2

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Contents

Table of Contents
C# PROGRAMMING.................................................................................................................................................. 1
TABLE OF CONTENTS...................................................................................................................................................3
STUDENT MACHINE SYSTEM REQUIREMENTS.......................................................................................................11
System Requirements using Microsoft Visual Studio .NET .............................................................................11
System Requirements using the Microsoft .NET Framework SDK..................................................................12
System Requirements using Linux and Ximian C#...........................................................................................12

INSTRUCTOR M ACHINE REQUIREMENTS................................................................................................................13


A DDITIONAL SETUP REQUIREMENTS......................................................................................................................13
Network.............................................................................................................................................................13
Example files .....................................................................................................................................................13

COURSE INTRODUCTION...................................................................................................................................15
INTRODUCTION TOPICS.............................................................................................................................................16
W HAT IS C# ................................................................................................................................................................17
OBJECTIVES ................................................................................................................................................................18
OUTLINE ......................................................................................................................................................................19
TOPICS NOT COVERED..............................................................................................................................................24
HOW PREPARED A RE YOU .......................................................................................................................................25
INTRODUCTIONS.........................................................................................................................................................26
COURSEWARE CONVENTIONS..................................................................................................................................27
CODE CONVENTIONS.................................................................................................................................................28
GENERAL ENVIRONMENT .........................................................................................................................................29
Class Exercise: Familiarize Yourself with the Online Documentation.....................................................30
Lab Exercise ........................................................................................................................................................31
MODULE 1: CLASSES, MAIN, CONSOLE INPUT/OUTPUT, AND OPERATORS ...........................33
M ODULE 1 TOPICS .....................................................................................................................................................34
EDITOR AND TEXT .....................................................................................................................................................35
M INIMAL C# PROGRAM ............................................................................................................................................36
C SHARP COMPILER (CSC) ........................................................................................................................................37
Class Exercise: Minimal Code.........................................................................................................................39
W HAT IS A CLASS? ....................................................................................................................................................40
THE MAIN METHOD....................................................................................................................................................41
CONSOLE INPUT AND OUTPUT .................................................................................................................................43
COMMENTS.................................................................................................................................................................45
BASIC DATA TYPES ....................................................................................................................................................46
STATEMENTS AND DECLARATIONS.........................................................................................................................47
OPERATORS.................................................................................................................................................................48
The Modulus Operator "%"...............................................................................................................................49
The Logical AND Operator "&"........................................................................................................................49
The Logical Short-Circuit AND Operator "&&" ..............................................................................................50
Increment Operators..........................................................................................................................................51
Overloaded Operators........................................................................................................................................51
Post vs. Pre Increment .......................................................................................................................................52

M ODULE 1 REVIEW....................................................................................................................................................53
Lab Exercise 1 .....................................................................................................................................................54
MODULE 2: DATA TYPES AND VALUE TYPE VARIABLES .................................................................55
M ODULE 2 TOPICS .....................................................................................................................................................56
DECLARING VARIABLES ...........................................................................................................................................57
VARIABLE NAMING...................................................................................................................................................58
TWO CATEGORIES OF DATA TYPES.........................................................................................................................59
BUILT -IN TYPES (SIMPLE TYPES) .............................................................................................................................60
CLS COMPLIANT SIMPLE TYPES .............................................................................................................................61
VALUE TYPES VS . REFERENCE TYPES ....................................................................................................................62
SIMPLE VALUE TYPES...............................................................................................................................................63
Copyright 2002 Third Millennium, LLP
C# Programming (Courseware #10010B)
http://www.thirdm.com - phone: (781)674-9720
3

Contents
VB6 versus C# Data Types................................................................................................................................63
C++ versus C# Data Types................................................................................................................................64
Java versus C# Data Types................................................................................................................................64
Value Types and Storage ...................................................................................................................................65
The bool Value Type.......................................................................................................................................66
Signed Integral Value Types .............................................................................................................................67
Unsigned Integral Value Types .........................................................................................................................68
The char Value Type.........................................................................................................................................69
Floating Point Value Types ...............................................................................................................................70

LITERALS.....................................................................................................................................................................71
Literal Suffixes ..................................................................................................................................................72
Hexadecimal and Scientific Literals ..................................................................................................................73

SIZE OF VALUE TYPES...............................................................................................................................................74


VALUE TYPES CONVERSION.....................................................................................................................................75
Implicit Conversion ...........................................................................................................................................76
Casting...............................................................................................................................................................77

U SER-DEFINED STRUCTURES (STRUCTS) VALUE TYPES .....................................................................................78


C# Built-In Types to .NET Framework struct Mapping....................................................................................79

.NET FRAMEWORK STRUCTS...................................................................................................................................80


ENUMERATION VALUE TYPES .................................................................................................................................81
INITIALIZZING VALUE TYPES...................................................................................................................................82
M ODULE 2 REVIEW....................................................................................................................................................83
Lab Exercise 2 .....................................................................................................................................................84
MODULE 3: REFERENCE TYPE VARIABLES .............................................................................................85
M ODULE 3 TOPICS .....................................................................................................................................................86
REFERENCE TYPES.....................................................................................................................................................87
THE OBJECT REFERENCE TYPE ................................................................................................................................88
REFERENCE TYPES STORAGE ...................................................................................................................................89
THE NULL VALUE.......................................................................................................................................................90
GARBAGE COLLECTION ............................................................................................................................................90
VALUE/REFERENCE STORAGE COMPARISON.........................................................................................................91
Object References ..............................................................................................................................................92

BOXING AND UNBOXING ..........................................................................................................................................93


THE STRING REFERENCE TYPE.................................................................................................................................94
REFERENCE TYPES FROM THE .NET FRAMEWORK CLASS LIBRARY .................................................................95
U SER DEFINED CLASSES...........................................................................................................................................96
A RRAY REFERENCE TYPES.......................................................................................................................................97
INTERFACE REFERENCE TYPES................................................................................................................................98
DELEGATE REFERENCE TYPES.................................................................................................................................99
M ODULE 3 REVIEW................................................................................................................................................. 100
Lab Exercise 3 ...................................................................................................................................................101
MODULE 4: STRINGS AND REGULAR EXPRESSIONS .........................................................................103
M ODULE 4 TOPICS .................................................................................................................................................. 104
ST RING CONCATENATION...................................................................................................................................... 105
CONVERTING STRINGS TO NUMBERS................................................................................................................... 106
TRIM, CLEANING UP STRINGS............................................................................................................................... 107
CHECKING FOR EQUALITY..................................................................................................................................... 108
The .Equals Method.........................................................................................................................................109

ESCAPE SEQUENCES ............................................................................................................................................... 110


Ignoring Escape Sequences .............................................................................................................................111

STRING FORMATTING ............................................................................................................................................. 112


REGULAR EXPRESSIONS......................................................................................................................................... 113
Regular Expressions (regex) ............................................................................................................................114
Regex Meta-Characters ...................................................................................................................................115
Complete Example...........................................................................................................................................116

M ODULE 4 REVIEW................................................................................................................................................. 117


Lab Exercise 4 ...................................................................................................................................................118
MODULE 5: BRANCHING AND CONDITIONAL LOOPING ................................................................121
C# Programming (Courseware #10010B)
Copyright 2002 Third Millennium, LLP
4
http://www.thirdm.com - phone (781) 674-9720

Contents
M ODULE 5 TOPICS .................................................................................................................................................. 122
LOGICAL OPERATORS............................................................................................................................................. 123
IF................................................................................................................................................................................ 124
if/else................................................................................................................................................................125
SWITCH/ CASE ........................................................................................................................................................... 126
WHILE........................................................................................................................................................................ 127

do/while ...........................................................................................................................................................128
FOR ............................................................................................................................................................................ 129
FOREACH .................................................................................................................................................................. 130
JUMP STATEMENTS................................................................................................................................................. 132

continue............................................................................................................................................................133
break ................................................................................................................................................................134
goto..................................................................................................................................................................135
return................................................................................................................................................................136
throw................................................................................................................................................................137

M ODULE 5 REVIEW................................................................................................................................................. 138


Lab Exercise 5 ...................................................................................................................................................139
MODULE 6: USING EXISTING CLASSES AND OBJECTS ....................................................................141
M ODULE 6 TOPICS .................................................................................................................................................. 142
CLASS VS. OBJECT .................................................................................................................................................. 143
INSTANTIATION ....................................................................................................................................................... 144
DECLARE REFERENCES.......................................................................................................................................... 145
PUTTING IT TOGETHER........................................................................................................................................... 146
GARBAGE COLLECTION ......................................................................................................................................... 147
Garbage Collection Illustrated.........................................................................................................................148

M ETHODS, PROPERTIES, AND EVENTS................................................................................................................. 149


M ETHODS................................................................................................................................................................. 150
INSTANCE M ETHODS .............................................................................................................................................. 151
THE RANDOM CLASS .............................................................................................................................................. 152
M ESSAGE PASSING ................................................................................................................................................. 153
Class Exercise: Roll the Dice .........................................................................................................................154
THE FILE INFO CLASS ............................................................................................................................................. 156
STREAMREADER CLASS ......................................................................................................................................... 157
EXAMPLE READING A FILE LINE BY LINE........................................................................................................... 158
STREAMW RITER CLASS ......................................................................................................................................... 159
INSTANCE PROPERTIES........................................................................................................................................... 160
Static Properties...............................................................................................................................................160
FileInfo Object Properties................................................................................................................................161

Class Exercise: Read A File............................................................................................................................162


STATIC M ETHODS AND FIELDS............................................................................................................................. 164
STATIC M ETHODS................................................................................................................................................... 165
File Class Static Methods................................................................................................................................166
Math Class Static Methods..............................................................................................................................167

STATIC FIELDS......................................................................................................................................................... 168


M ODULE 6 REVIEW................................................................................................................................................. 169
Lab Exercise 6 ...................................................................................................................................................170
MODULE 7: EXCEPTION HANDLING ..........................................................................................................171
M ODULE 7 TOPICS .................................................................................................................................................. 172
DEFINE AN EXCEPTION .......................................................................................................................................... 173
Exception Abuse..............................................................................................................................................173

EXCEPTION EXAMPLE ............................................................................................................................................ 174


EXCEPTION HANDLING WITH TRY /CATCH ........................................................................................................... 175
TYPES OF EXCEPTIONS........................................................................................................................................... 176
Exception Hierarchy ........................................................................................................................................177

M ULTIPLE CATCH BLOCKS.................................................................................................................................... 178


THE FINALLY BLOCK.............................................................................................................................................. 179
OVERFLOW EXCEPTION AND CHECKED VERSUS UNCHECKED............................................................................... 180
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


5

Contents
U SER-DEFINED EXCEPTION SCENARIO................................................................................................................ 182
MissingSalaryException..................................................................................................................................183
Handling Exceptions........................................................................................................................................184
Nested try/catch blocks....................................................................................................................................184

W HEN USE EXCEPTION HANDLING?.................................................................................................................... 185


EXCEPTION CONSTRUCTORS................................................................................................................................. 186
GENERATING EXCEPTIONS .................................................................................................................................... 187
W RAPPING EXCEPTIONS ........................................................................................................................................ 188
M ODULE 7 REVIEW................................................................................................................................................. 189
Lab Exercise 7 ...................................................................................................................................................190
MODULE 8: USING ARRAYS .............................................................................................................................193
M ODULE 8 TOPICS .................................................................................................................................................. 194
A RRAYS A RE OBJECTS........................................................................................................................................... 195
M EMORY REQUIREMENTS..................................................................................................................................... 196
Memory Illustrated..........................................................................................................................................197

A CCESS TO A RRAY DATA...................................................................................................................................... 198


A SSIGNING VALUES TO AN A RRAY...................................................................................................................... 199
A RRAYS OF CLASS TYPE........................................................................................................................................ 200
Arrays Of Class Type: Memory ......................................................................................................................201

STRING M ETHODS................................................................................................................................................... 202


String.Join ........................................................................................................................................................203
Join Example ...................................................................................................................................................204
String.Split .......................................................................................................................................................205
Split Example...................................................................................................................................................206

M ULTI-DIMENSIONAL A RRAYS............................................................................................................................ 207


Arrays Of Arrays: Jagged ................................................................................................................................208

M ODULE 8 REVIEW................................................................................................................................................. 209


Lab Exercise 8 ...................................................................................................................................................210
MODULE 9: USING COLLECTIONS...............................................................................................................211
M ODULE 9 TOPICS .................................................................................................................................................. 212
SYSTEM.COLLECTIONS .......................................................................................................................................... 213
A RRAYLIST .............................................................................................................................................................. 214
Using foreach With ArrayList.........................................................................................................................215
ICollection interface ........................................................................................................................................216
IList interface...................................................................................................................................................217

STACK ....................................................................................................................................................................... 218


QUEUE ...................................................................................................................................................................... 219
HASHTABLE ............................................................................................................................................................. 220
IDictionary Interface........................................................................................................................................221
Hashtable methods...........................................................................................................................................222
Hashtable properties ........................................................................................................................................223

IENUMERATOR INTERFACE.................................................................................................................................... 224


M ODULE 9 REVIEW................................................................................................................................................. 225
Lab Exercise 9 ...................................................................................................................................................226
MODULE 10: STRUCTS AND ENUMS ............................................................................................................227
M ODULE 10 TOPICS................................................................................................................................................ 228
PURPOSE OF STRUCT TYPES.................................................................................................................................. 229
.NET FRAMEWORK STRUCTS................................................................................................................................ 230
Point.................................................................................................................................................................231
System.DateTime.............................................................................................................................................232
System.TimeSpan............................................................................................................................................233

U SER DEFINED STRUCT ......................................................................................................................................... 234


STRUCT CONSTRUCTORS ....................................................................................................................................... 235
U SING A CUSTOM STRUCT ..................................................................................................................................... 236
DEFINITE A SSIGNMENT .......................................................................................................................................... 237
PURPOSE OF ENUM (ENUMERATION).................................................................................................................... 238
SYSTEM.DAYOFW EEK ENUM ............................................................................................................................... 239
C# Programming (Courseware #10010B)
6

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Contents
U SING AN ENUM...................................................................................................................................................... 240
SYSTEM.TYPECODE ENUM .................................................................................................................................... 241
TypeCode Example .........................................................................................................................................242

U SER DEFINED ENUM............................................................................................................................................. 243


Custom enum base data type...........................................................................................................................244
Starting value ...................................................................................................................................................244
Calculated value...............................................................................................................................................244

U SING ENUMS TO DEFINE INSTANCE MEMBERS .................................................................................................. 245


M ODULE 10 REVIEW .............................................................................................................................................. 246
Lab Exercise 10.................................................................................................................................................247
MODULE 11: CLASSES, FIELDS, AND PROPERTIES .............................................................................249
M ODULE 11 TOPICS................................................................................................................................................ 250
W HY CLASSES A RE USED ..................................................................................................................................... 251
CLASS M EMBERS .................................................................................................................................................... 252
COMMON MEMBERS............................................................................................................................................... 253
INSTANTIATION AND MEMBER INITIALIZATION ................................................................................................. 254
STATE ....................................................................................................................................................................... 255
Instance Fields Are Used To Maintain an Object's State................................................................................255

INSTANCE FIELDS.................................................................................................................................................... 256


Sample Class with Private Data.......................................................................................................................257
Private Data.....................................................................................................................................................258

PROPERTIES PROVIDE DATA A CCESS .................................................................................................................. 259


Access to the Data: Properties .........................................................................................................................260
Properties That Veto Access............................................................................................................................261

A CCESS LEVELS ...................................................................................................................................................... 262


Access Levels for Internal Use........................................................................................................................263
Access Levels for Subclasses ..........................................................................................................................264
Access Level for Full Exposure.......................................................................................................................265

STATIC FIELDS......................................................................................................................................................... 266


A CCESS TO STATIC FIELDS.................................................................................................................................... 267
OTHER FIELDS......................................................................................................................................................... 268
M ODULE 11 REVIEW .............................................................................................................................................. 269
Lab Exercise 11.................................................................................................................................................270
MODULE 12: METHODS, CONSTRUCTORS, AND INDEXERS ..........................................................271
M ODULE 12 TOPICS................................................................................................................................................ 272
M ETHOD................................................................................................................................................................... 273
Method Signature.............................................................................................................................................274
Method with No Return Value ........................................................................................................................275

STATIC M ETHODS BELONG TO THE CLASS ......................................................................................................... 276


INSTANCE M ETHODS BELONG TO AN OBJECT .................................................................................................... 277
M ETHOD OVERLOADING........................................................................................................................................ 278
M ETHOD PARAMETER KEYWORDS: REF AND OUT ............................................................................................. 279
ref versus out....................................................................................................................................................280

M ETHOD PARAMETER KEYWORDS: PARAMS...................................................................................................... 281


CONSTRUCTOR ........................................................................................................................................................ 282
Constructor Signature ......................................................................................................................................283
The Default Constructor...............................................................................................................................284

STATIC CONSTRUCTOR .......................................................................................................................................... 285


CONSTRUCTOR OVERLOADING............................................................................................................................. 286
INDEXERS................................................................................................................................................................. 288
Multiple Indexers.............................................................................................................................................289

M ODULE 12 REVIEW .............................................................................................................................................. 290


Lab Exercise 12.................................................................................................................................................291
MODULE 13: INHERITANCE AND VIRTUAL METHODS ....................................................................293
M ODULE 13 TOPICS................................................................................................................................................ 294
A BASE CLASS......................................................................................................................................................... 295
The Employee Base Class ...............................................................................................................................296

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


7

Contents
A SUBCLASS ............................................................................................................................................................ 297
The SalaryEmployee Class..............................................................................................................................298
The Director Class...........................................................................................................................................299
The HourlyEmployee Class.............................................................................................................................300

POLYMORPHISM ...................................................................................................................................................... 301


Polymorphism Using References ....................................................................................................................302

CASTING REFERENCES........................................................................................................................................... 303


Casting References Illustrated.........................................................................................................................304

U SING IS AND AS..................................................................................................................................................... 305


SUBCLASS CONSTRUCTORS SYNTAX.................................................................................................................. 306
Invoking an Inherited Constructor...................................................................................................................307

M ETHOD OVERRIDING ........................................................................................................................................... 308


The virtual Modifier ........................................................................................................................................310
The override Modifier......................................................................................................................................311
Invoking Overridden Base Class Methods ......................................................................................................312
Polymorphic Methods......................................................................................................................................313

BYPASSING POLYMORPHISM USING NEW............................................................................................................ 314


THE ABSTRACT M ODIFIER....................................................................................................................................... 315
The sealed Modifier ....................................................................................................................................315

COMMONLY OVERRIDDEN METHODS INHERITED FROM SYSTEM.OBJECT .................................................... 316


The ToString Method......................................................................................................................................316
The Equals Method..........................................................................................................................................317
The GetHashCode Method..............................................................................................................................318

DEFINING OPERATOR OVERLOADING.................................................................................................................. 319


Using an Overloaded Operator........................................................................................................................320
Object.ReferenceEquals...................................................................................................................................320

M ODULE 13 REVIEW .............................................................................................................................................. 321


Lab Exercise 13.................................................................................................................................................322
MODULE 14: INTERFACES ................................................................................................................................323
M ODULE 14 TOPICS................................................................................................................................................ 324
PURPOSE OF AN INTERFACE................................................................................................................................... 325
INTERFACE M EMBERS............................................................................................................................................ 326
INTERFACE EXAMPLE ............................................................................................................................................. 327
IMPLEMENTATION ................................................................................................................................................... 328
Guarantee Behavior .........................................................................................................................................329

U SING AN INTERFACE............................................................................................................................................. 330


M ULTIPLE INTERFACES.......................................................................................................................................... 331
Interface Conflict .............................................................................................................................................332

EXPLICIT INTERFACE IMPLEMENTATION ............................................................................................................. 333


Forwarding Method.........................................................................................................................................335

INTERFACE PROPERTIES......................................................................................................................................... 336


INTERFACE INDEXERS ............................................................................................................................................ 337
COMPLETE EXAMPLE ............................................................................................................................................. 338
INTERFACE EVENT S................................................................................................................................................. 339
.NET FRAMEWORK INTERFACES THAT ALLOW FOREACH TO LOOP THROUGH YOUR COLLECTION............ 340
IEnumerator the Hard Way..............................................................................................................................341
IEnumerator the Easy Way..............................................................................................................................342

M ODULE 14 REVIEW .............................................................................................................................................. 343


Lab Exercise 14.................................................................................................................................................344
MODULE 15: DELEGATES AND THREADS ................................................................................................345
M ODULE 15 TOPICS................................................................................................................................................ 346
W HAT IS A DELEGATE?......................................................................................................................................... 347
THE THREAD CLASS ............................................................................................................................................... 348
INSTANTIATING THE DELEGATE ........................................................................................................................... 349
THREAD M ETHODS................................................................................................................................................. 350
Complete Example: the Bouncing Ball ...........................................................................................................351
Complete Example: Many Balls Bouncing .....................................................................................................352

U SER DEFINED DELEGAT E .................................................................................................................................... 353


C# Programming (Courseware #10010B)
8

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Contents
Example: Declaring, Instantiating, and Invoking a Delegate..........................................................................354
Example: Invoking Delegates One at a Time ..................................................................................................355

M ULTICAST DELEGATE.......................................................................................................................................... 356


Example: Multicast Invocation........................................................................................................................357

M ODULE 15 REVIEW .............................................................................................................................................. 358


Lab Exercise 15.................................................................................................................................................359
MODULE 16: USING WINDOWS FORMS TO WRITE A WINDOWS APPLICATION ................361
M ODULE 16 TOPICS................................................................................................................................................ 362
U SING SYSTEM.WINDOWS.FORMS; ...................................................................................................................... 363
SUB-CLASSING FORM AND APPLICATION.RUN ()............................................................................................... 364
Minimal Example ............................................................................................................................................365

COMMON CONTROLS.............................................................................................................................................. 366


THE BUTTON CLASS ............................................................................................................................................... 367
Form Constructor.............................................................................................................................................368
Button Example ...............................................................................................................................................369

FORM M ENU ............................................................................................................................................................ 370


Menu Hierarchy...............................................................................................................................................371
Menu Example.................................................................................................................................................372

M ODULE 16 REVIEW .............................................................................................................................................. 373


Lab Exercise 16.................................................................................................................................................374
MODULE 17: EVENTS ..........................................................................................................................................375
M ODULE 17 TOPICS................................................................................................................................................ 376
W HAT IS AN EVENT ?.............................................................................................................................................. 377
EVENT HANDLER DELEGATE................................................................................................................................. 378
THE EVENT KEYWORD ........................................................................................................................................... 379
SYSTEM.WINDOWS.FORMS.CONTROL................................................................................................................. 380
EVENT HANDLER METHODS ................................................................................................................................. 381
SYSTEM.WINDOWS.FORMS.M ESSAGE BOX......................................................................................................... 382
COMPLETE EVENT EXAMPLE ................................................................................................................................ 383
U SER DEFINED EVENTS......................................................................................................................................... 384
User Defined Event Example ..........................................................................................................................385
User Defined Event Example (continued) .......................................................................................................386

M ODULE 17 REVIEW .............................................................................................................................................. 387


Lab Exercise 17.................................................................................................................................................388
MODULE 18: NAMESPACES, ASSEMBLIES, AND WRITING CLASS LIBRARY DLLS ..........389
M ODULE 18 TOPICS................................................................................................................................................ 390
NAMESPACE............................................................................................................................................................. 391
A SSEMBLY ............................................................................................................................................................... 393
Modules ...........................................................................................................................................................394

NAMESPACE VS. A SSEMBLY.................................................................................................................................. 395


A SSEMBLY SECURITY............................................................................................................................................. 396
COMMON PRACTICE ............................................................................................................................................... 397
U SING A SSEMBLIES AND NAMESPACES............................................................................................................... 398
CREATING A CLASS LIBRARY DLL...................................................................................................................... 399
U SING CLASS LIBRARY DLL ................................................................................................................................ 400
Class Exercise: Disassemble ..........................................................................................................................401
PRIVATE VS. SHARED A SSEMBLIES...................................................................................................................... 402
STRONG NAME ........................................................................................................................................................ 403
GLOBAL A SSEMBLY CACHE (GAC)..................................................................................................................... 404
CREATING A SHARED A SSEMBLY......................................................................................................................... 405
M ODULE 18 REVIEW .............................................................................................................................................. 406
Lab Exercise 18.................................................................................................................................................407
MODULE 19: ATTRIBUTES AND PREPROCESSOR DIRECTIVES ...................................................409
M ODULE 19 TOPICS................................................................................................................................................ 410
ATTRIBUTES............................................................................................................................................................. 411
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


9

Contents
ATTRIBUTE SYNTAX............................................................................................................................................... 412
ATTRIBUTE TARGETS............................................................................................................................................. 413
PRE -DEFINED ATTRIBUTES ................................................................................................................................... 414
CLSCompliantAttribute...................................................................................................................................415
SerializableAttribute........................................................................................................................................416
WebMethodAttribute.......................................................................................................................................417

U SER-DEFINED ATTRIBUTES ................................................................................................................................. 419


Using custom attributes ...................................................................................................................................420

A CCESSING CUSTOM ATTRIBUTES USING REFLECTION ................................................................................... 421


PREPROCESSOR DIRECTIVES ................................................................................................................................. 422
Common Preprocessor Directives ...................................................................................................................423
Directive Example ...........................................................................................................................................424

CONDITIONAL COMPILATION USING ATTRIBUTES ............................................................................................ 425


M ODULE 19 REVIEW .............................................................................................................................................. 426
Lab Exercise 19.................................................................................................................................................427
MODULE 20: NETWORKING ............................................................................................................................429
M ODULE 20 TOPICS................................................................................................................................................ 430
DNS AND IPHOST ENTRY ....................................................................................................................................... 431
IPA DDRESS .............................................................................................................................................................. 432
URI ........................................................................................................................................................................... 433
THE SYSTEM.URI CLASS ........................................................................................................................................ 434
W EBREQUEST .......................................................................................................................................................... 435
W EBRESPONSE ........................................................................................................................................................ 436
WebRequest Complete Example .....................................................................................................................437

M ODULE 20 REVIEW .............................................................................................................................................. 438


Lab Exercise 20.................................................................................................................................................439
MODULE 21: XML MANIP ULATION .............................................................................................................441
M ODULE 21 TOPICS................................................................................................................................................ 442
SAMPLE XML DOCUMENT .................................................................................................................................... 443
XML Document Tree ......................................................................................................................................444

XMLDOCUMENT...................................................................................................................................................... 445
XMLTEXT READER AND XMLVALIDATINGREADER.......................................................................................... 446
ValidationEventHandler ..................................................................................................................................447

XMLDOCUMENT MEMBERS ................................................................................................................................... 448


XMLELEMENT CLASS ............................................................................................................................................. 449
XMLNODELIST COLLECTION................................................................................................................................. 450
XML SERIALIZATION ............................................................................................................................................. 451
Schema-based persistence ...............................................................................................................................452
SOAP-based persistence..................................................................................................................................453
Writing an XML instance to a file...................................................................................................................454
Reading an XML instance from a file .............................................................................................................455

XML DOCUMENTATION ........................................................................................................................................ 456


Generating XML Documentation....................................................................................................................457
XML Documentation tags ...............................................................................................................................458
Verified XML Documentation tags .................................................................................................................459
Verified Tag Example......................................................................................................................................460

M ODULE 21 REVIEW .............................................................................................................................................. 461


Lab Exercise 21.................................................................................................................................................462
COURSE REVIEW ..................................................................................................................................................463
OBJECTIVES REVIEW.............................................................................................................................................. 464
W HAT 'S NEXT .......................................................................................................................................................... 465
RESOURCES .............................................................................................................................................................. 466
INDEX ..........................................................................................................................................................................467

C# Programming (Courseware #10010B)


10

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Contents

Student Machine System Requirements


These instructions are needed by the people who set up the classroom for training.
Students and instructors can also use these instructions to set up their work and/or home
machines to practice the exercises included in this course.
This course has been designed to teach C# either using the Microsoft Visual Studio .NET
IDE (Integrated Development Environment) or any standard text editor along with the
Microsoft .NET Framework SDK (Software Development Kit). The .NET Framework
SDK is available as a free 130 MB download from Microsofts developer web site at
http://msdn.microsoft.com/netframe work/.
This course focuses on learning to program with the C# language regardless of where or
how it is used. This course does include special instructions that are tailored to the
Microsoft operating systems, notably Windows 2000, but this material can be used to
teach C# on Linux or other operating systems using 3rd party compilers such as the mono
project's MVC, the Ximian C# compiler, available at http://www.go- mono.org. This
course does not focus on development tools either graphical or command line. When
appropriate, instructions are offered for both the Microsoft command line SDK tools and
the Microsoft Visual Studio IDE.
System Requirements using Microsoft Visual Studio .NET
If you are using Visual Studio .NET in the classroom, it is recommended that you have
the following system:

Windows 2000 Professional SP2 (Service Pack 2)


256 MB RAM
Pentium II, 800 MHz
5 GB free hard drive space available on a single drive before installation
Visual Studio .NET Professional Edition or Visual C# .NET Standard Edition and
MSDN online documentation installed on a local hard drive (such as the C: drive)

Visual Studio .NET is available in several different versions including Professional,


Enterprise, and Enterprise Architect. You can also install it on Windows NT 4.0 SP6a,
Windows 2000 Server, and Windows XP. If your classroom does not have the above
recommended system requirements, check Microsofts Visual Studio .NETs minimum
requirements at http://msdn.microsoft.com/vstudio/. For example, it is possible with
Windows 2000 Professional to install Visual Studio .NET with only 96 MB of RAM but
it is not recommended. Visual C# .NET Standard Edition is also available as a stand
alone product and does not require the purchase of the full Visual Studio .NET which
bundles Visual Basic .NET and Visual C++ .NET with Visual C# .NET.
Warning: Visual Studio .NET and the .NET Framework SDK will not work with
Windows 95, Windows 98, or Windows ME. Be sure that Windows NT 4 SP6a,
Windows 2000, Windows XP, or Windows .NET is installed on the computer before
attempting to install Visual Studio .NET or the .NET Framework SDK.
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


11

Contents

System Requirements using the Microsoft .NET Framework SDK


If you are using a generic editor and the SDK command line compiler tools, it is
recommended that you have the following system:

Windows NT 4.0 Workstation SP6a (Service Pack 6a)


128 MB RAM
Pentium II, 600 MHz
700 MB free hard drive space available before installation
Internet Explorer 6.0
Microsoft Data Access Components 2.7
any ASCII editor such as UltraEdit (www.ultraedit.com)
.NET Framework SDK installed on a local hard drive (such as the C: drive)

Although any editor will work, we recommend UltraEdit since it is not very expensive
and has built in support for syntax highlighting in C#. A 45-day trial version is available
for free at http://www.ultraedit.com.
The .NET Framework SDK should modify the PATH environment variable at install time.
To ensure that the path has been setup correctly, logout and log back in using the student
account. Open a new Command Prompt window and type:
csc /?

If the command responds with a list of options, then the PATH environment variable has
been correctly modified. If the command responds with a message such as 'csc' is not
recognized as an internal or external command, operable program or batch file, then the
PATH environment variable is incorrectly modified.
If the PATH is not properly modified because the option was not selected at install time,
it is important tha t the PATH environment variable is modified to include the path to
csc.exe. This can be done in the System Control Panel under the Environment tab on
NT 4 or the Advanced tab (press button labeled "Environment Variables") on Windows
2000. You must modify either the User's PATH or the System's PATH. It is better to
modify the System's PATH because that will affect all user logins for the machine (in
case a student logs in with a different account). To locate the directory that contains
csc.exe you can use Start: Search: For files or folders. It should be located in a
directory like:
C:\WINNT\Microsoft.NET\Framework\v1.0.3705

System Requirements using Linux and Ximian C#


Although this course has not been tested with other C# implementations, such as the
Mono projects MCS, the Ximian C# compiler, (http://www.go- mono.org) it should be
possible to use other operating systems such as Linux or Unix and an editor like vi or
emacs. We have no recommended system requirements for this setup. Please consult the
Mono project web site for more details.
C# Programming (Courseware #10010B)
12

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Contents

Instructor Machine Requirements


The instructor machine should match the student machines but must also include Adobe
Acrobat Reader, available free from http://www.adobe.com, if the instructor will be using
the slides. Acrobat is used to display the slides from the instructor machine connected to
a projection device. Adobe Acrobat reader has a full-screen view mode that allows you
to navigate from one slide to another using the arrows or page-up/page-down keys.

Additional Setup Requirements


Classroom setup includes the following additional setup requirements:
Network
It is highly recommended to have a classroom of networked computers, preferably
connected to the Internet. Use of the Internet is used in the Networking module.
Example files
Example files in this book are available on CD-ROM and should be installed prior to
class start or during class on the first day. The example files are organized by module
number and can be opened with any text editor, including the Visual Studio .NET editor.
The example files should be extracted using WinZip (http://www.winzip.com) to a
directory on the hard drive called student. For Windows 2000 machines the
recommended directory would be:
C:\student

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


13

Introduction

Introduction
C# Programming

C# Programming

Course Introduction

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


15

Introduction

Introduction Topics
n What

is C#
n Objectives
n Outline and Modules
n What's Not Covered
n Prerequisites
n Introductions
n General Environment
C# Programming

Slide 3

copyright 2001 - Third Millennium, LLP

Introduction Topics
This chapter includes a general overview of C#, the course objectives, a list of course
modules, the prerequisites, general material layout, and the student environment.
The outline for this course is the list of module titles. This introduction sets the
expectations of the topics that will be covered in the course by reviewing the module
chapter titles. A module is similar to a chapter but is designed to be used as an
independent learning unit. Each module is designed to be independent of other modules,
but due to the C# programming language's complexity, many modules assume
understanding of topics covered in previous modules.
This module also introduces the courseware conventions, coding conventions, and
includes an in class instructor led exercise to locate and use the .NET Framework and C#
language online documentation found on the computer (not the Web).
This course introduction module ends with a lab exercise which students will work on
their own to locate topics in the online documentation. This exercise is designed to
familiarize students with the classroom and computer environment and requires no
coding.

C# Programming (Courseware #10010B)


16

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

What is C#
n
n
n
n
n
n

Part of Microsoft's .NET Framework


CLS Compliant Language
Language for writing ASP.NET pages and Web
Services
Evolution of C and C++
Multipurpose Language similar to Java
Fits between Visual Basic and Visual C++ in the
Microsoft Visual Studio development suite
C# Programming

Slide 4

copyright 2001 - Third Millennium, LLP

What is C#
C# is a programming language specifically designed for Microsofts .NET Framework.
The C# programming language was jointly submitted as a proposed standard to ECMA,
an international standards organization, on October 31st , 2000 by Hewlett-Packard, Intel
Corporation, and Microsoft. The ECMA General Assembly of December 13th , 2001
approved Standards ECMA-334, C# (C sharp) Language Specification, and ECMA-335,
Common Language Infrastructure.
C# complies to the CLS. CLS is the Common Language Specification, which allows
many languages that comply with this spec in order to interoperate with each other at
design and runtime. For example, you can write a class in C++ with Managed Extensions
extend it in VB.NET and then extend it again in C#. This is not exclusive to Microsoft
languages. Theoretically in the future you can write a Perl.NET class extend it or use it
from SmallTalk-2000 (SmallScript) and extend it again in Fijutsu COBOL for .NET.
ASP.NET offers the ability to write full blown C# (similar to what is capable in JSP with
Java) and now also full blown VB (not just VBScript) with the advantage of a compiled
instead of interpreted language for improved performance of your server-side logic on
behind your web pages.
C# can be used to solve many problems, from notebook applications to very large server
systems.
Visual C++ is known for its raw power, but unfortunately with power comes complexity
and complexity brings less productivity. Visual Basic is known for its high productivity
RAD (Rapid Application Development) capabilities, but with that comes less power and
control. C# has been designed to fit between the power of C++ and the simplicity of VB.
C# merges the high productivity with raw power.
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


17

Introduction

Objectives
n Understand

C# Language Fundamentals
n Use .NET objects and classes
n Define custom structs, enums, objects and
classes
n Design classes with properties, methods,
indexers, and events
n Communicate over the internet and web
n Manipulate XML
C# Programming

Slide 5

copyright 2001 - Third Millennium, LLP

Objectives
By the end of this course you will have a good understanding of the C# language
fundamentals. You will be able to use the .NET Framework, class library (FCL), define
custom types, and write classes with properties, indexers, methods, and events. You will
also be able to use C# to communicate over the internet and web. Finally, you will be
able to use C# to read, traverse, and generate XML.

C# Programming (Courseware #10010B)


18

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

Outline, Part 1
Modules 1 to 4
Classes, Main, Operators, Input/Output
2. Data Types and Value Type Variables
3. Reference Type Variables
4. Strings and Regular Expressions
1.

C# Programming

Slide 6

copyright 2001 - Third Millennium, LLP

Outline
The course is broken up into five parts. Each part consists of 4 to 5 modules each. Each
part will typically take one day including time to work on the included lab exercises and
any additional exercises provided by the instructor.
Module 1: Classes, Main, Operators, Input and Output. In this module we will be
setting up environment: either Visual Studio.NET or an editor and command line
compiler in order to test the canonical HelloWorld program. We will learn the building
blocks and a starting point of a C# application. We will learn basic console input and
output. Finally, we will cover the basic operators used in arithmetic, string, and Boolean
operations.
Module 2: Data Types and Value Type Variables We will discuss the difference
between value and reference types, initializing variables, boxing/unboxing. We will also
learn that in C#, everything is an object.
Module 3: Reference Type Variables In this chapter we introduce the different types of
reference variables. These include strings, classes, interfaces, and delegates.
Module 4: Strings and Regular Expressions In this chapter we will cover some of the
built in functionality of strings and use simple regular expressions to search for a pattern
in a string.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


19

Introduction

Outline, Part 2
Modules 5 to 9
5.
6.
7.
8.
9.

Branching and Conditional Looping


Using Existing Classes and Objects
Exception Handling
Using Arrays
Using Collections

C# Programming

Slide 7

copyright 2001 - Third Millennium, LLP

Module 5: Branching and Conditional Looping This module covers the basic if,
while, for, foreach, and switch/case constructs.
Module 6: Using Existing Classes and Objects In this module we look at the Random,
Math, File , and FileInfo classes that are available in the .NET Framework class
library. This module is designed to get you more comfortable with using classes and
objects before we design our own.
Module 7: Exception Handling In this module we learn how to trap errors and handle
them using try/catch/finally blocks. We will also throw our own exceptions when
something unexpected happens enabling the caller to handle the exception.
Module 8: Using Arrays This chapter teaches us how to create and use one dimensional
and two dimensional arrays of various data types.
Module 9: Using Collections Here we learn how to create dynamic arrays by using
the .NET Framework collection classes such as ArrayList, Stack, Queue, and
Hashtable.

C# Programming (Courseware #10010B)


20

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

Outline, Part 3
Modules 10 to 13
Structs and Enums
11. Classes, Fields, and Properties
12. Methods, Constructors, and Indexers
13. Inheritance and Virtual Methods
10.

C# Programming

Slide 8

copyright 2001 - Third Millennium, LLP

Module 10: Writing Structs and Enums In this module we will build C++ like structures
and enumerators and use structs and enums in the .NET Framework Class Library.
Module 11: Classes, Fields, and Properties This chapter will focus on writing our own
classes. We will build struct- like classes with fields and Properties to create state. We
will learn how to use the static, readonly, and const modifiers. We will learn the
different access modifiers for members: public through private.
Module 12: Methods, Constructors, and Indexers In this chapter we will establish
behavior for our objects. Methods allow objects to perform actions. Constructors allow
our objects to be created with special initialization routines. Indexers allow our objects to
behave like arrays and hash tables.
Module 13: Inheritance and Virtual Methods In this module we will learn how to
subclass a base class to reuse code and allow for polymorphic behavior through virtual
method invocation. We will also learn how to overload operators so our objects can have
additional object-oriented behavior when used with C#s built- in operators.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


21

Introduction

Outline, Part 4
Modules 14 to 17
Interfaces
15. Delegates and Threads
16. Using Windows Forms to Write a
Windows Application
17. Events
14.

C# Programming

Slide 9

copyright 2001 - Third Millennium, LLP

Module 14: Interfaces In this module we will create polymorphic behavior using
unrelated classes regardless of their hierarchy. This is a powerful feature of any language
that allows us to declare behavior semantics without forcing any specific implementation.
We will also use the .NET Framework interfaces to create an object that can be used by
the foreach loop to iterate through its members.
Module 15: Delegates and Events - creating a first class component with events
(properties and methods)
Module 16: Using Windows forms to write a Windows Application- This chapter focuses
on the basic classes required to create a Windows GUI (Graphical User Interface) for
your application using forms and controls.
Module 17: Events This chapter teaches us how to respond to and raise events in our
GUI and non-GUI applications.

C# Programming (Courseware #10010B)


22

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

Outline, Part 5
Modules 18 to 21
Namespaces, Assemblies, and Writing
Class Library DLLs
19. Attributes and Preprocessor Directives
20. Networking
21. XML Manipulation
18.

C# Programming

Slide 10

copyright 2001 - Third Millennium, LLP

Module 18: Namespaces, Assemblies, and Writing Class Library DLLs - Focusing on
creating class libraries, we will use namespaces which are important for complex projects.
We will also create our own reusable libraries and store them in dynamic link library
(DLL) files as private class libraries. We will also learn how to create shared libraries by
registering our library in the GAC (Global Assembly Cache).
Module 19: Attributes and Preprocessor Directives This module focuses on using a new
declarative programming feature called attributes. Attributes allow meta- information to
adorn constructs such as classes and methods. We will see examples of .NET Framework
Class Library attributes and create our own custom attributes. C# also has compiler
emulation of certain preprocessor directives familiar to C++ programmers. We will learn
how to use preprocessor directives to conditionally compile parts of our code.
Module 20: Networking Critical in today's applications, this chapter covers some basic
classes for DNS, URL, and IP address functionality. We will also use classes to connect
to web servers and download content from the web.
Module 21: XML Manipulation XML has become the universal data format for
interoperability. This chapter looks at the built- in C# language functionality such as
XML documentation, and DOM manipulation. We will also use the .NET Framework to
serialize and persist our objects using SOAP and XML Schema serialization formats.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


23

Introduction

Topics Not Covered


n Programming

Basics
n Detailed coverage of Visual Studio.NET
IDE, such as debugging, IDE macros
n Unsafe Code
n Microsoft Intermediate Language (MSIL)
n Advanced C#

C# Programming

Slide 11

copyright 2001 - Third Millennium, LLP

Topics Not Covered


Programming basics are not covered. You must be an experienced programmer to take
this course. This is not an introduction to programming course.
Detailed coverage of the Visual Studio.NET IDE is not covered. This course focuses on
the C# language which is accessible to developers who work with editors and command
line compilers or IDE users. When appropriate, suggestions are made when the course
delivery environment uses an IDE offering instructions of where on the menu to find
certain options. The instructor may choose to add any IDE or command line tips that will
help you learn the C# language.
Unsafe code is not covered. C# allows for C type pointers which are considered unsafe.
The performance is not significantly increased as demonstrated in Eric Gunnerson's book
"A Programmer's Introduction to C#" but benchmarking can be used when performance
is critical to determine if unsafe code is worth the loss of type safety.
MSIL is the intermediate language that C# compiled code is assembled into. It is a
language similar to Java bytecode or VB6 P-code. We will not cover MSIL, only C#.
Advanced C# is not part of this course. This thorough course is designed to give the
attendants a strong foundation of the C# language and prepare the attendants for
advanced C# topics.

C# Programming (Courseware #10010B)


24

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

How Prepared Are You


n Experienced

programmer in any language


n Experienced programmer in one of the
following languages is recommended

C++
Java
Visual Basic
Perl

n Familiarity

with object-oriented concepts is


strongly recommended

C# Programming

Slide 12

copyright 2001 - Third Millennium, LLP

How Prepared Are You


Experienced Programmer - this is not a course for non-programmers
Understand Objects - C# is object-oriented, objects can take time to understand for
programmers who have never dealt with them. Programmers who use procedural
languages such as C, Assembly, COBOL, or Pascal often do not work with objectoriented systems or concepts. You may find some of the object-oriented subject
challenging if you have no object-oriented experience.
Can you write programs in: C++, Visual Basic, Java, or Perl?
C++ - if you have C++ experience, you should find C# very familiar. If you are only
familiar with C you may have difficulties when the object-oriented topics are covered.
Visual Basic - due to being a novice friendly language, a VB programmer who does not
know how to write VB interfaces and classes with methods and properties might have
difficulties with some subjects
Java - if you have Java experience, you should find C# very familiar, although many
features from C++ may not be familiar.
Perl - if you have Perl experience but have only worked with small basic scripts you may
have a challenging time with data types and object-oriented development. If you have
developed object-oriented Perl modules you will be better prepared for C#.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


25

Introduction

Introductions
n Name
n Programming

experience
n Job responsibility
n Current or future projects that relate to C#
n Reasons for enrolling in the course

C# Programming

Slide 13

copyright 2001 - Third Millennium, LLP

If you have only worked with typeless scripting languages such as VBScript, JavaScript,
and Perl, you may have a challenging time with C#, unless you have used the more
complex features in these languages such as VBScript classes, or object-oriented
JavaScript features, or object-oriented Perl modules.
If your only experience with computers is writing HTML, this does not qualify for
programming experience unless you have programmed JavaScript blocks imbedded in
HTML using the <script> tag.

Introductions
This is an opportunity for each of the attendees to give the instructor some background to
why you are attending this course. This information is important for the instructor to fine
tune the delivery to the whole class experience level.

C# Programming (Courseware #10010B)


26

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

Courseware Conventions
n

Typographical convention examples and fonts


code will appear: Bold Courier

reserved words, code examples, .NET classes and methods

placeholders: Italic Bold Courier or

<Bold Courier>
optional in brackets: [Bold Courier]
comments: // Bold Courier
erroneous code: Bold Courier // Error
Symbols
Construct definitions from the .NET documentation or
.NET class introductions are followed by:
C# Programming

Slide 14

copyright 2001 - Third Millennium, LLP

Courseware Conventions
These conventions are used in this book so you can identify the code examples,
intentionally erroneous code used to demonstrate when certain statements fail, optional or
placeholders, and comments. Courier font is used to represent code. Code in italics or
angle brackets is used as place holders. When describing syntax, square brackets signify
optional code such as parameters or modifiers.
There is a special symbol used to identify .NET Framework classes, types, methods, and
other constructs that can be further researched in the .NET Framework class library
documentation. Use of this symbol can also help you distinguish the material external to
C# and found in the .NET Framework from aspects of the language itself. It is important
to remember that the C# language was designed from the start to run inside the .NET
Framework runtime and therefore, many of C#'s functionality is intertwined with
the .NET Framework.
Another note is that whenever you see the .NET Framework symbol, this should also
remind you that these constructs are available not only to C# programmers but also,
VB.NET, Visual C++ with Managed Extensions, and even other languages designed to
run in the CLR (Common Language Runtime) such as ActiveState's Perl.NET and Fujitsu
COBOL.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


27

Introduction

Code Conventions
n curly

braces will follow Microsoft default


when space allows for it
void myMethod()
{
// next line open brace, Visual C# default
}
void myMethod() {
// end of line open brace
// used to conserve space in the course slides
}

n
n

- used for private members


PascalCase - used for public members
camelCase

C# Programming

Slide 15

copyright 2001 - Third Millennium, LLP

Code Conventions
This course is designed to follow the Microsoft C# coding conventions whenever
possible. In order to fit more source code example text on the slides, the end-of- line open
brace convention is used instead of the Visual C# default next line open brace.
If you are using Visual Studio.NET and you do not want to use the Microsoft default, you
can customize the environment by choosing Tools: Options: Text Editor: C#: Formatting:
Leave open braces on same line as construct.
Camel casing is used to declare local and private variable and methods. Public constructs
such as classes, methods, properties, and public fields use the Pascal casing convention.
These conventions have replaced older coding conventions such as using underscore and
Hungarian notation. Please refer to the .NET Frame work documentation topic
under .NET Framework Developer Specifications called .NET Framework Design
Guidelines for more details.

C# Programming (Courseware #10010B)


28

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

General Environment
n Class

Hours
n Lecture and Class Exercises
n Lab Exercises (on your own)
n Breaks and Lunch
n Restrooms, Phones, Food, and other
Facilities
n Computers, Login Accounts, etc
n Questions
C# Programming

Slide 16

copyright 2001 - Third Millennium, LLP

General Environment
This course is designed to be a mix of lecture (which includes class exercises) and lab
exercises that follow. The class exercises allow you to follow the instructor during
demonstrations to become familiar with a specific topic. At the beginning there are
several class exercises. As the course progresses, you will do most of the exercises on
your own.
The lab exercises are at the end of each module.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


29

Introduction

Class Exercise
(with the instructor)
n Find

the online documentation for C#


language reference
n Find the online documentation for the .NET
Framework Design Guidelines
n Find the documentation for the Object
class
n Find the DateTime struct
Find the Ticks property
Find the Addition operator
C# Programming

Slide 17

copyright 2001 - Third Millennium, LLP

Class Exercise: Familiarize Yourself with the Online Documentation


Follow the instructor's instructions to find the items listed above.
Online documentation is available in two forms: as local files on your system or html
documents from msdn.microsoft.com. We will assume you are using local online docs.
Online in this context does not refer to on the network but rather on the computer.
Offline documentation would include traditional paper based books.
If you are using Visual Studio, the help menu will give you access to the MSDN library.
If you are using an editor and the command line console, you may find documentation
under the Start: Programs menus usually labeled .NET SDK.

C# Programming (Courseware #10010B)


30

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Introduction

Lab Exercise
(on your own)
n Find

the documentation for


System.Console
How do you read in from standard input?
How do you write out to standard error?

n Find

the Math class

n Find

the square root function

C# Programming

Slide 18

copyright 2001 - Third Millennium, LLP

Lab Exercise
The purpose of this exercise is to familiarize you with the online documentation. This
exercise requires no programming.
Using the documentation available on the computer, find the documentation on the
System.Console class.
How do you read in from standard input? Don't worry about the code you must write,
just look for the appropriate method.
Find the appropriate class or method for writing to standard error.
Find the Math class. The Math class is located in the System namespace. The square
root function is found in the Math class.
Ask your instructor for help if you are unable to locate any of these items.
This exercise will help you become familiar with the online documentation, which is
critical to exploiting the full power of C# and the .NET Framework. Knowing how to
navigate and understand this documentation is one of the most important skills a C#
programmer can have.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


31

Module #1 Classes, Main, Console I/O, Operators

Module 1
Classes, Main, Console I/O,
Operators

C# Programming

Module 1: Classes, Main, Console Input/Output, and


Operators

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


33

Module #1 Classes, Main, Console I/O, Operators

Module 1 Topics
Classes, Main, Console Input/Output, and Operators
n
n
n
n
n
n
n
n

Set up environment
Write, Compile, and Run a minimal C# program
Understand the purpose of a class
The Main method
The System namespace
Use Console input and output
Comments
Basic Operators
C# Programming - Classes, Main, Console I/O, Operators

Slide 2

copyright 2001 - Third Millennium, LLP

Module 1 Topics
In this module, we will begin by getting comfortable with our environment, by either
opening up Visual Studio.NET or an editor and writing our first program together. We
will then compile, and run the minimal "Hello World" program. This class exercise will
get you comfortable with the programming environment and give you the opportunity to
set up or fine tune your system.
Once we have compiled our first program, we will discuss the purpose of a class. We
will learn how a class is used as a template for creating an object. It is also the container
for our Main method.
The Main method is the starting point for our program. We will learn the different
signatures possible for the Main method.
The System namespace is part of the .NET Framework where many of our standard
types can be found such as String, Object, and DateTime .
The Console class is useful for input and output. We will use the ReadLine and
WriteLine methods of the Console class as well as the Error property to access
standard in, standard out, and standard error streams.
We will learn the three types of comments: end-of- line, multi- line, and XML
documenting comments.
Finally, we will cover the basic operators for arithmetic, logic, string, and assignment
operations.
C# Programming (Courseware #10010B)
34

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Editor and Text


n
n
n

C# is Case Sensitive
Whitespace and new lines are mostly ignored
Layout:
Start with zero or more using statements
and/or namespace blocks
Followed by one or more classes, structs,
enums, interfaces, and/or delegates
Any text editor will work: notepad, ultraedit, etc
C# Programming - Classes, Main, Console I/O, Operators

Slide 3

copyright 2001 - Third Millennium, LLP

Editor and Text


Similar to C++ but unlike VB, new lines in C# are only cosmetic not functional. C# is
case sensitive. If you are a VB programmer, be very careful with lower and upper case
characters. For example:
x = 5;
X = 6;
are two different variables.
There are some cases where new lines will be significant such as the special literal @
strings which are covered in a later module.
New lines in the source code are used to terminate single line comments.
Using statements are similar to Java import statements, C++ include statements, and Perl
use and require statements. Using statements allow you to make a connection between
your code and external code. In C# this external code is often found in the .NET class
library. The using statements can go before or inside a namespace block. The using
statement must precede and can not be placed inside a class, struct, enum , or
interface block.
Note that the layout may include namespaces which is covered in a later module in more
detail.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


35

Module #1 Classes, Main, Console I/O, Operators

Minimal C# Program
class Minimal
{
static void Main()
{
System.Console.WriteLine("Hello");
}
}

n Save

the file as: Minimal.cs

n Note:

Main must have a capital "M"

C# Programming - Classes, Main, Console I/O, Operators

Slide 4

copyright 2001 - Third Millennium, LLP

Minimal C# Program
Here we are declaring a class called Minimal. Inside our class we have a Main method.
The Main method must be spelled with a capital M and must be preceded by the static
modifier. Immediately preceding the method name Main is the return type of this method.
The return type for Main can be either void (returns nothing and return statement is
implicit at the end of the block) or int (must return a valid int at the end of the Main
method. Example: return 1;)
Our program must include one Main method for the program to be executable. The Main
method may inc lude an optional string[] for command line arguments. Arrays are
covered in a later chapter.
Here are two other examples of what you can type. The using statement allows you to
abbreviate the WriteLine statement.
using System;
class Minimal2
{
static void Main()
{
Console.WriteLine("Hello");
}
}
example files:
mod01_main\minimal.cs
mod01_main\minimal2.cs

C# Programming (Courseware #10010B)


36

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

C Sharp Compiler (csc)


n Command

line using CSC:

>csc Minimal.cs
output generated: Minimal.exe
n Using

a menu or button on your IDE

Visual Studio.NET

C# Programming - Classes, Main, Console I/O, Operators

Slide 5

copyright 2001 - Third Millennium, LLP

or create an alias for System.Console


using Out=System.Console;
class Minimal3
{
static void Main() {
Out.WriteLine(Hello);
}
}

All three basically do the same thing. The using declaration allows access to other
namespaces and classes without having to fully qualify the
Namespace.Classname.Method.
example files: mod01_main\minimal3.cs

C Sharp Compiler (csc)


If you are using the command line tools make sure the PATH environment variable has
been set to find it. A simple test is to simply type csc /? at the command line. csc
should respond with a list of options. Use Start > Search > For Files or Folders... and
look for "csc.exe ". It will probably be in the system directory:
C:\WINNT\Microsoft.NET\Framework\v1.0.2914\csc.exe

Visual Studio.NET is a fully functional IDE for C# development and no special setup is
required to compile.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


37

Module #1 Classes, Main, Console I/O, Operators

Run the Program


n

Command line:
>Minimal

n
n

Or choose Start from


menu or button bar
Output should display
Hello

You may want to use "Start Without


Debugging" because it will pause the
program before it terminates

C# Programming - Classes, Main, Console I/O, Operators

Slide 6

copyright 2001 - Third Millennium, LLP

To run the program, simply type the name of the executable, in this case Minimal, at the
command line and hit enter. If you are using Visual Studio, click on the Debug menu and
either use "Start" or "Start Without Debugging". The second choice is better when
testing console applications. Later we will see how you can add two lines to the end of
the Main method to pause the program before it terminates by using the
Console.ReadLine. That way you can use "Start" (with debugging).
Note: you must compile this program on a machine with either Visual Studio.NET
installed or just the .NET Framework SDK. Since the .NET Framework SDK is smaller
and has less system requirements, this may be your choice. The SDK Beta 2 only runs on
Windows NT, Windows 2000, and Windows XP. To execute the program, you do not
need the SDK, you can run the program on a computer with .NET Framework
redistributable package installed. The redistrib utable runs on Windows 98 and above.
Check http://msdn.microsoft.com/net for the latest information and downloads.

C# Programming (Courseware #10010B)


38

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Class Exercise: Minimal Code


(with the instructor)
n

Enter the Minimal C# program in either an editor or Visual


Studio.NET, compile and test (run the program)
class Minimal {
static void Main() {
System.Console.WriteLine("Hello");
}
}

Change the file to test aliasing, compile and run


using Cmd = System.Console;
class Minimal {
static void Main() {
Cmd.WriteLine("Hello");
}
}

Change the using statement to:


using System;
C# Programming - Classes, Main, Console I/O, Operators

Slide 7

copyright 2001 - Third Millennium, LLP

Class Exercise: Minimal Code


Follow the instructor's directions for getting the minimal program entered, compiled and
running.
Test the minimal C# program, and make sure it works. If you are using the Visual Studio
environment, you can start with a new C# Console project by choosing File > New
Project... off the menu. Name your project "Module01". Visual Studio will insert the
namespace Module01 and name your class Class1, you should either delete the entire
contents and retype or omit the unwanted sections manually. Be sure to have an equal
number of open braces as closing braces. If you choose to leave in the namespace, that is
fine. We will cover the benefits of namespaces in a later module.
This exercise demonstrates that the using statement can create an alias for the class
System.Console and call it "Cmd ".
using Cmd = System.Console;

Once the file has been entered, compiled, and executed (tested), change the using
statement to:
using System;

You will need to make a change the WriteLine statement as well. The line should read:
Console.WriteLine("Hello");

Recompile and test. Make sure it works.


Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


39

Module #1 Classes, Main, Console I/O, Operators

What is a Class?
n A class

is a unit of code

nA

class is also a blueprint for creating an


object
n A class is a data type
n Classes can have static methods which
behave like functions and do not require an
instance (object)
n Main is a static method
C# Programming - Classes, Main, Console I/O, Operators

Slide 8

copyright 2001 - Third Millennium, LLP

What is a Class?
A class is a unit or capsule of code. All of the variables and methods inside a class are
called members. These members are encapsulated inside the class.
A class is not only a capsule of code but is also a template for instantiating objects
(instances). Objects are discussed later in more detail.
A class is a data type. You can use a class type when declaring a variable. Since
variables in C# must always be declared with a specific type, you can use any class name
as the variable type. The next two modules cover all of the intrinsic data types available
in C# in detail.
static is used in both VB and C++ to imply that it sticks around like the static

electricity that sticks a sock to a shirt after coming out of the dryer. C# has a similar
meaning for the word static. Static methods, like Main, are always available. You do not
need to instantiate the class to invoke a static method. Nor do you need to worry about it
going away. The opposite of a static method is an instance method. Both are members,
but the static method "belongs to" the class where an instance method "belongs to" an
object.
Since instance methods "belong to" an object, they are not available until we create an
object. When the object reference is lost, the object goes away (it is actually garbage
collected). Once you loose access to your object, you can no longer invoke its instance
methods. Static methods, like functions, don't require objects to invoke.

C# Programming (Courseware #10010B)


40

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

The Main Method


n The

starting point
n Is static because it is executed directly
The runtime environment will not create an
object from your class unless you explicitly do
so in your code
n Does

not need to be public


n Returns either void or int
n Takes either no arguments or a string[]
C# Programming - Classes, Main, Console I/O, Operators

Slide 9

copyright 2001 - Third Millennium, LLP

The Main Method


Your program starts with the Main method. Main can take on any of the following
forms:
static void Main() { ... }
static void Main(string[] argv) { ... }
static int Main()
{
...
return 0;
}
static int Main(string[] argv) {
...
return 0;
}

Arrays and methods are covered in more detail in later modules. The second choice uses
a string array called argv to read in command line arguments. The third and forth
choices allow you to return zero as an exit code indicating that no error occurred, or by
returning a non-zero such as one or two to indicate that a certain error occurred during
execution. Error codes are commonly used when writing command line utilities in UNIX.
There are several other possible signatures for your Main method. You can combine the
second and third choices to enable command line arguments and a error code. You can
also expose the method with higher access visibility using internal, protected or
public modifiers in front of the static modifier. If no access modifier is specified,
such as in our example, the Main method is private. We will cover access modifiers in
more detail later.
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


41

Module #1 Classes, Main, Console I/O, Operators

System.Console.WriteLine
n

System is a namespace where many

classes and structures live such as Console


Console is a class that encapsulates the
standard in, and standard out functionality
of the command window
WriteLine is a static method that belongs
to the Console class and is used for writing
output to the command window (stdout)
C# Programming - Classes, Main, Console I/O, Operators

Slide 10

copyright 2001 - Third Millennium, LLP

The Console's In, Out, and Error properties can be used for UNIX like piping as well.
When you add a using System; declaration to the beginning of a source code
document, the compiler will automatically search the System namespace when trying to
find classes that your code refers to. Therefore you do not need to type
System.Console to refer to the Console class, you only need to type Console.
The WriteLine method comes in several forms. We are using it to print a single string.
Other versions allow you to use a formatted string with placeholders for objects similar to
the C language's printf function.

C# Programming (Courseware #10010B)


42

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Console Input and Output


n Input
Console.ReadLine()
string color = Console.ReadLine();

n Output

format string with placeholders

Console.Write("my output");
object
Console.WriteLine("my output");
Console.WriteLine("my format {0}", var);
Console.Error.WriteLine("my output");

C# Programming - Classes, Main, Console I/O, Operators

Slide 11

copyright 2001 - Third Millennium, LLP

Console Input and Output


Here are several examples of using Console methods. The Console.Write method
does not put a new line character after your output versus Console.WriteLine which
does. Console.Error.WriteLine writes text out to the standard error stream.
By default, standard error and standard output are both directed to the console window in
a console application. The following two lines in the Main method below might appear
to have the same effect unless you redirected the error stream to a separate file.
// compile: csc ErrorMessage.cs
// execute: ErrorMessage 2> err.log
using System;
class ErrorMessage
{
static void Main()
{
Console.Out.WriteLine("This is a message to STDOUT");
Console.Error.WriteLine("This is a message to STDERR");
}
}

Redirecting standard error to a log file is possible in the NT/2000/XP console which
behaves very similar to a UNIX console. Attempting to redirect standard error on
Windows 98/ME using the above execute command will fail.
example files:
mod01_main\error.cs
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


43

Module #1 Classes, Main, Console I/O, Operators

Input and Output Example


static void Main()
{
Console.Write("What is your name? ");
string user = Console.ReadLine();
string place = "the program";
Console.WriteLine("Welcome {0} to {1}.", user, place);
}

placeholders for objects

C# Programming - Classes, Main, Console I/O, Operators

objects

Slide 12

copyright 2001 - Third Millennium, LLP

Because the Console.WriteLine method uses the standard output stream by default the
following two lines have identical effect:
Console.WriteLine("my output");
Console.Out.WriteLine("my output");

You can add the following two lines to the end of the Main method of a Console
application being developed in Visual Studio.NET in order to use the Debug > Start
menu command instead of Debug > Start Without Debugging:
Console.Write("program end. hit enter:");
Console.ReadLine();

C# Programming (Courseware #10010B)


44

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Comments
// this is an end of line comment
/* this is a
multi-line comment */
/// <remarks> this is an XML
/// documentation comment</remarks>

C# Programming - Classes, Main, Console I/O, Operators

Slide 13

copyright 2001 - Third Millennium, LLP

Comments
Here is a commented version of the Minimal program:
using System;
// Minimal is the class name
class Minimal
{
// Main is the starting point of my program
static void Main()
{
/* Console.WriteLine is short for
* System.Console.WriteLine
* which is possible because this source code
* file starts with a using System; declaration
*/
Console.WriteLine(Hello);
} // end of Main
} // end of class declaration

Module 21: XML Manipulation covers the XML documentation comments in more detail.
example files:
mod01_main\comments.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


45

Module #1 Classes, Main, Console I/O, Operators

Basic data types


n

a sequence of characters
a whole number
either true or false

string
int
bool

Must declare before assign value and use

string message;
message = "hello";
Console.WriteLine(message);
n

Other data types will be covered later


C# Programming - Classes, Main, Console I/O, Operators

Slide 14

copyright 2001 - Third Millennium, LLP

Basic data types


C# has 15 built- in data types. These are 3 common data types that will be used in the
following slides demonstrating the C# operators. Modules 2 and 3 cover these data types
and more in more detail.
C# is unlike JavaScript, Visual Basic 6 or Perl because it is required that you declare your
variables and initialize them before you attempt to print them. VB6 has the Option
Explicit statement and Perl has use strict; pragma to force declaration. Because C#
requires you to declare your variables before you use them, you will encounter less
runtime bugs as a result of typos. Variable typos will be caught by the compiler.
C# is similar to Java and C++. Declarations must precede variable usage always.

C# Programming (Courseware #10010B)


46

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Statements and Declarations


n Terminated

by a semi-colon ";"

if (x > 5) y = 10;
n Sometimes

terminated by a block { }

if (x > 5) { y = 10; }
n Can

include variable declarations and


assignments in same statement
int x = 5;

C# Programming - Classes, Main, Console I/O, Operators

Slide 15

copyright 2001 - Third Millennium, LLP

Statements and Declarations


Here is an example of a simple conditional statement ending with a semi-colon:
if (x > 5) y = 10;

Using blocks allow you to create a compound statement. In other words, a compound
statement is a statement that is made up of other statements.
if (x > 5)
{
y = 10;
z = 15;
}

Statements can be variable declarations, variable assignments, or both. Unlike VB6, it is


legal to declare and assign an initial value to a variable.
int x = 5;

is the same as:


int x;
x = 5;

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


47

Module #1 Classes, Main, Console I/O, Operators

Operators
n Arithmetic
n Logical
n Bitwise,

Shifting

+
&
&

|
|

*
^
^

/ %
! && ||
~ << >>

n String

+
n Increment, Decrement ++ -n Relational
== != < > <= >=
n Assignment
=
+= -= *=
/= %=
&= |= ^= <<= >>=
C# Programming - Classes, Main, Console I/O, Operators

Slide 16

copyright 2001 - Third Millennium, LLP

Operators
This is a list of common C# operators broken into categories. We will cover a few
arithmetic, logical, increment, and assignment operators.

+
*
/
%
&
|
^
!
&&
||
&
|
^
~
<<
>>
+

Arithmetic
add
subtract
multiply
divide
modulus
Logical
AND
OR
XOR
not
short-circuit AND
short-circuit OR
Bitwise, Shifting
bitwise AND
bitwise OR
bitwise XOR
bitwise compliment
bitwise shift left
bitwise shift right
String
concatenation

C# Programming (Courseware #10010B)


48

++
-==
!=
<
>
<=
>=
=
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=

Increment, Decrement
auto-increment
auto-decrement
Relational
equals
not equa ls
less than
greater than
less than or equals
greater than or equals
Assignment
assignment
add (or concatenate) and assign
subtract and assign
multiply and assign
divide and assign
modulus and assign
AND and assign
OR and assign
XOR and assign
bitwise shift left and assign
bitwise shift right and assign
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Operator Examples
n Modulus
int
int
int
int

operator: % (remainder in division)

apples = 14;
people = 3;
perPerson = apples / people; // 4
leftover = apples % people;
// 2

n Logical

AND operator: &

bool registered = true;


int age = 25;
bool canVote = registered & (age >= 18);
C# Programming - Classes, Main, Console I/O, Operators

Slide 17

copyright 2001 - Third Millennium, LLP

The Modulus Operator "%"


The modulus operator, %, returns the remainder in integer division.
int apples = 14;
int people = 3;
int perPerson = apples / people;
Console.WriteLine( perPerson ); // displays 4
int leftover = apples % people;
Console.WriteLine( leftover ); // displays 2

The Logical AND Operator "&"


The logical AND operator, &, requires both sides to evaluate to true in order to result in a
true outcome. If either side of the & operator is false, the entire outcome is false.
bool registered = true;
int age = 25;
bool canVote = registered & (age >= 18);
if (canVote) {
Console.WriteLine("voter is registered");
Console.WriteLine(" and ");
Console.WriteLine("voter is 18 or older");
}
example files:
mod01_main\modulus.cs
mod01_main\logicaland.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


49

Module #1 Classes, Main, Console I/O, Operators

More Operator Examples


n Short-circuit

AND operator: &&

string message = null;


bool bigMessage =
(message != null) && (message.Length > 10);

n Left

hand side is evaluated first


n Right hand side is only evaluated if
necessary
n What would happen if the && was replaced
with an & operator?
C# Programming - Classes, Main, Console I/O, Operators

Slide 18

copyright 2001 - Third Millennium, LLP

The Logical Short-Circuit AND Operator "&&"


The logical short-circuit AND operator, &&, will only evaluate the right hand side if the
outcome can not be determined by the left hand side. This is also true with the logical
short-circuit OR operator, ||.
string message = null;
bool bigMessage = message != null && message.Length > 10;

Don't worry if you do not understand the access of the Length property. We will cover
using objects and properties in more detail later. This is only to demonstrate the fact that
the right hand side of the operation will result in an error if message is null. The shortcircuit operator prevents the right hand side from being evaluated by testing the left hand
side first.
Question: What would happen if the && was replaced with an & operator?
Answer: An error would result. If the message is null then the first test in front of the
&& returns false. Since the result of a logical AND operation requires both to be true,
the short circuit operator skips the evaluation of the right hand side. If the && was
replaced with a single &, the right is always evaluated. If you try to access the Length
property of string that does not exist (null) C# returns a runtime error.

example files:
mod01_main\shortcircuitand.cs

C# Programming (Courseware #10010B)


50

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Increment and Overloaded


Operators
n Increment

and short-cut assignment

int counter = 5;
counter = counter + 1;
counter += 1;
counter++;

// counter=6
// counter=7
// counter=8

n The

+ operator is overloaded to have


another meaning, concatenation
string message = "hello ";
message += "world";

C# Programming - Classes, Main, Console I/O, Operators

Slide 19

copyright 2001 - Third Millennium, LLP

Increment Operators
There are several ways to increment a variable. The traditional way (counter = counter
+1) the short cut (counter += 1) and the auto- increment (counter++). The + operator
when used with numbers does an arithmetic operation. When used with strings, the +
operator is overloaded to perform string concatenation.
Overloaded Operators
C# allows you to overload operators when you define your own types to perform the
appropriate behavior. We will cover operator overloading in Module 13: Inheritance and
Virtual Methods.

example files:
mod01_main\increment.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


51

Module #1 Classes, Main, Console I/O, Operators

Post vs. Pre Increment


n Post-increment
int counter = 5;
int item = counter++;
Console.WriteLine(item);

// displays 5

n Pre-increment
int counter = 5;
int item = ++counter;
Console.WriteLine(item);

C# Programming - Classes, Main, Console I/O, Operators

// displays 6

Slide 20

copyright 2001 - Third Millennium, LLP

Post vs. Pre Increment


When the double plus sign ++ follows the variable, the auto- increment happens after the
initial value of the variable is used in the statement.
When the double plus sign ++ precedes the variable, the auto- increment happens before
the value of the variable is used in the statement.
In the two examples above, the value of counter is assigned to the item variable.. In each
case the auto-increment is used differently to demonstrate its effect on the statement it
occurs in.

example files:
mod01_main\prevspost.cs

C# Programming (Courseware #10010B)


52

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #1 Classes, Main, Console I/O, Operators

Module 1 Review
Classes, Main, Console Input/Output, and Operators
n
n
n
n
n
n
n

You can use any editor and the command line csc compiler or the
Visual Studio.NET to develop C# applications
The purpose of a class is a container of code and a template for an
object
The Main method is a static method and serves as the starting
point of your application
The System namespace contains many useful classes and types
including the Console class
Use Console for input: ReadLine and output: WriteLine
3 types of comments // single-line, /* multi-line */, and
/// XML documentation
Basic operators include + , - , * , /, and & to provide arithmetic
Boolean, and string operations
C# Programming - Classes, Main, Console I/O, Operators

Slide 21

copyright 2001 - Third Millennium, LLP

Module 1 Review
In this chapter we learned how to compile a simple C# program with either the command
line or the Visual Studio environment.
We also learned about classes, the Main method, and the System.Console class.
For basic input and output, the Console class comes with static methods for reading and
writing lines of text.
C# allows for three types of comments. Two types from C++ and a third type for XML
documentation which is covered in more detail in the XML module.
We were introduced to basic operators for arithmetic, logical, string, and assignment
operations.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


53

Module #1 Classes, Main, Console I/O, Operators

Lab Exercise 1
(on your own)
n
n

Try naming the class something different than the


filename and see if it still compiles and runs.
Try to use the command line options or the Visual
Studio project properties to generate an exe of a
different name then the source file name. Use
csc /help

Try creating an alias for System.Console but call


it stdout so the WriteLine looks like:
stdout.WriteLine("hello world");
C# Programming - Classes, Main, Console I/O, Operators

Slide 22

copyright 2001 - Third Millennium, LLP

Lab Exercise 1
Step #1: Rename the class in your source file, but do not rename the file. For example
call the class Hello and keep the source file name Minimal.cs. Compile and test. Does
it still work? There are no rules for naming filenames after class names in C# like there
is in Java.
Step #2: When you compile Minimal.cs, try to see if the resulting exe file can be called
something other than Minimal.exe, for example try to see if you can generate the
executable called First.exe. If you are using csc, you should use the command line
options. If you are using Visual Studio.NET, use the project properties.
Step #3: During the class exercise you created an alias for System.Console, try doing
it again on your own. This time call it stdout.
Step #4: If you finish early, try experimenting with math operators doing basic math
using int types.

C# Programming (Courseware #10010B)


54

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Module 2
Data Types and Value Type
Variables

C# Programming

Module 2: Data Types and Value Type Variables

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


55

Module #2: Data Types and Value Type Variables

Module 2 Topics
Data Types and Value Type Variables

n Learn

how to declare variables


n Introduced to the two type categories
Value type
Reference type
n Learn

the complete list of built-in types


n Understand all of the simple value types
n Introduction to struct and enum types
C# Programming - Data Types and Value Type Variables

Slide 2

copyright 2001 - Third Millennium, LLP

Module 2 Topics
In this module, we will learn more about declaring variables. We will also learn the
difference between the two categories of data types: value type and reference type.
We will cover the complete list of the 15 built- in data types.
We will also be introduced to struct and enum types, both of which are value types. We
will spend more time in a later module creating our own structs and enums.

C# Programming (Courseware #10010B)


56

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Declaring Variables
n
n

Must declare variables before use


Declaration requires a data type

datatype varname;
string x;
n

May declare multiple variables together

datatype varname1, varname2;


string str1, str2, str3;
n

Optionally you can assign an initial value

datatype varname = initval;


int y = 5;
C# Programming - Data Types and Value Type Variables

Slide 3

copyright 2001 - Third Millennium, LLP

Declaring Variables
Detailed coverage of the different data types follow. This slide uses string (a sequence
of characters) and int (a 32 bit integer) for examples of declaring variables.
When you declare a variable in C#, you must specify the data type. In VB6 variables can
be declared without a data type. This is called loosely typed or weak data typing. Many
scripting languages such as Perl, VBScript, and JavaScript are loosely typed. C# is
strongly typed. All variables must be declared with a specific data type.
You may declare multiple variables together separated by commas. All variables
declared together take on the same type. Also, you may assign an initial value to the
variable as in the example:
int y = 5;

You may not declare a variable twice in the same block. Local variables are declared in a
method block or inside a nested block such as a loop block. Member variables are
declared in a class block.
In Visual Basic 6 and older you are not allowed to declare and assign an initial value to a
variable in the same statement except for constants. VB.NET allows the same type of
declare and initialize in the same statement, just like C#.
For the purpose of discussing variables, we will focus on local variables for the length of
this module. These variables will be declared in the Main method.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


57

Module #2: Data Types and Value Type Variables

Variable Naming
n

Naming convention
Use camelBack for any variable that are hidden (local
and private variables)
Use PascalStyle for variables that are exposed with
the public modifier

n
n
n

Start with a letter


Combination of letters, numbers, and underscore
Can not be keyword
Unless you use the @ prefix (discouraged)
int @int = 5;
C# Programming - Data Types and Value Type Variables

Slide 4

copyright 2001 - Third Millennium, LLP

Variable Naming
PascalCase uses capital letters for the first character in each word and avoids underbars.
For example:
Employee , BackupFile, OpenNextRecord, FirstName

camelCase uses capital letters for each word except the first word in the variable name.
For example:
employee , backupFile, openNextRecord, firstName

Private variables, method parameters, local variables, private methods and other private
members not exposed to the outside should follow camelCase. Anything exposed outside
of the class should follow the PascalCase naming convention. It is important when
writing C# code that is CLS compliant that public members do not differ in case alone.
CLS allows multiple language access to a common class. Since Visual Basic is case
insensitive, it can not differentiate between two public methods that differ in case alone.
Private data and behavior names do not need to follow any CLS compliance since they
are not exposed to other languages such as Visual Basic.
.

C# Programming (Courseware #10010B)


58

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Two Categories of Data Types


n Value

Types

Simple types (excluding object and string)


Enumerations (enum)
Structures (struct)
n Reference

Types

The object and string simple types


Classes
Interfaces
Arrays

C# Programming - Data Types and Value Type Variables

Slide 5

copyright 2001 - Third Millennium, LLP

Other conventions:
- do not use an underscore in class and interface names
- do not prefix classes with the letter C (common in Visual Basic)
- do prefix interfaces with the letter I (also common in Visual Basic)
- do suffix exception classes with Exception (common in Java)
- do suffix attribute classes with Attribute
- do use nouns when naming classes
- do use verbs when naming methods
Please refer to the .NET Framework documentation topic under .NET Framework
Developer Specifications called .NET Framework Design Guidelines for more details

Two Categories of Data Types


Value types (simple types excluding object and string, enums, and structs) are stored on
the stack. Therefore these types are faster and do not require garbage collection.
Reference types (object, string, class, interface and array types) are stored on the heap.
Value types are only stored on the stack if they are local variables. Instance
variables (member variables) are part of an object and are therefore stored on the heap.
Reference variables are stored on the stack, but the data they reference is on the
heap. An example is an employee object or even a string object. The employee reference
can be a local variable, the employee name, id, favorite color are stored on the heap.
Structs are basically objects on the stack. More detail will be covered later.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


59

Module #2: Data Types and Value Type Variables

Built-in Types (simple types)


n

Universal
object (anything and everything)

Text based
string (sequence of characters)
char (a single character)

Logical
bool (true or false)

Numeric
int, float, double, etc...
C# Programming - Data Types and Value Type Variables

Slide 6

copyright 2001 - Third Millennium, LLP

Built-in Types (simple types)


The built- in types are part of the C# language and are reserved as keywords. Here is the
full list of built- in types (also called simple types):
Reference types: object, string
Value types: char, bool, sbyte, byte, short, ushort, int, uint, long, ulong,
float, double, decimal

C# Programming (Courseware #10010B)


60

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

CLS Compliant Simple Types


bool

System.Boolean (true or false)

char

System.Char (2-byte unsigned integer)

byte

System.Byte (1-byte unsigned integer)

short

System.Int16 (2-byte signed integer)

int

System.Int32 (4-byte signed integer)

long

System.Int64 (8-byte signed integer)

float

System.Single (4-byte floating point number)

double

System.Double (8-byte floating point number)

decimal

System.Decimal (12-byte floating point number)

string

System.String (A string of zero or more characters; null is allowed.)

object

System.Object (The root of all class inheritance hierarchies)

C# Programming - Data Types and Value Type Variables

Slide 7

copyright 2001 - Third Millennium, LLP

CLS Compliant Simple Types


This table displays two columns. On the left is the C# built- in type, on the right is
the .NET Framework struct/class. System.String and System.Object are classes,
the rest are structs. These types are available to any CLS compliant language. Their
names may be different. For example, the float type in C# is equivalent to the VB.NET
Single type. They both refer to the same underlying type: System.Single.
The Common Language Specification (CLS) includes certain types. These types can be
used to have multiple languages inter-operate with each other through the Common
Language Runtime (CLR).
Limit your usage to these simple types only when exposing the public interface to other
the Runtime system and other programmers who write programs that use your interface
from another language such as VB.NET, Perl, Smalltalk, or Fujitsu COBOL. This will
allow them to call your methods and inherit from your classes.
Internally in your private usage, feel free to use any and all of the C# data types without
affecting portability and cross-language compatibility.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


61

Module #2: Data Types and Value Type Variables

Value Types vs. Reference Types


n Value

types (int, char, float)

Stored on the stack


Good for small quick data
Direct access to data
n Reference

types (string, object)

Stored on the heap


Good for complex data
Access data from reference (a safe pointer)
C# Programming - Data Types and Value Type Variables

Slide 8

copyright 2001 - Third Millennium, LLP

Value Types vs. Reference Types


There are two main memory areas in the C# runtime, the stack and the heap. The stack is
a place where local variables are "stacked up". Every time a second method is called the
current method, the stack grows to hold local variables declared in the second method.
The stack continues to grow every time a method is called. When the method returns the
stack shrinks when the local variables go out of scope. The second main memory area is
the heap. The heap is a large place in memory that is used to store objects. When a
method returns and the local variables go out of scope, stack is cleared of value type
variables but the objects created on the heap and referenced with reference variables
remain. The garbage collector is a special .NET Runtime process that runs in the
background of your program that is responsible for removing old objects on the heap.
Value types are often quicker because they are stored directly on the stack when they are
used to declare local variables. Later we will use value types defined within a class as
member variables (member field s). When value types are used to declare member fields
in a class, these variables live on the heap because they are part of an object. The entire
object is accessed through a reference variable.
Because reference variables are stored on the stack but the data the variables refer to are
on the heap, reference types are slower. Occasionally reference types are faster and
require less memory when you have many reference variables all pointing to the same
object on the heap. If you were to use a complex value type and pass it around to many
different methods, the runtime would be required to copy the data over and over on the
stack, wasting time and memory. It is always important to analyze your data types and
test them in real or high load situations to make sure you are using the most appropriate
data types. The rest of this module focuses on value types. Reference types are covered
in the next module.
C# Programming (Courseware #10010B)
62

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Simple Value Types


n
n

Logical (true/false only, numbers not allowed)


bool
Integral (0,1,2,3)
sbyte, short, int, long (signed)
byte , ushort, uint, ulong (unsigned)
char (unsigned integer)
Floating Point (0.0001, 2.3E+34, PI)
float, double
decimal
C# Programming - Data Types and Value Type Variables

Slide 9

copyright 2001 - Third Millennium, LLP

Simple Value Types


Simple value types are sometimes called basic types. These types are built- in to the C#
language and have notations for their literal values as part of the language.
VB6 versus C# Data Types
Visual Basic programmers may recognize 4 of these (byte, double, long , and
decimal). Two of these are identical: byte and double. The long type in C# has no
VB equivalent. The Long type in VB is the same as the int type in C#. Decimal is
virtually the same except for C#s decimal is 16 bytes vs. VBs Decimal which is 14
bytes in size. VBs Boolean type is similar to the C# bool type except that VB uses a
numeric storage of -1 for true and 0 for false. C# does not have any numeric association
with the bool type.
VB6

C#

Byte
Double
Decimal
Single
Integer
Long
Boolean
Currency
Date
Object
Variant
String

byte
double
decimal
float
short
int
bool
decimal
DateTime
object
object
string

Relationship
identical
identical
almost identical
different name
different name
different name
different name, more restrictive
different name, bigger range in C#
different name, C# uses the .NET Framework struct
VB6 Object is more restrictive
similar
similar

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


63

Module #2: Data Types and Value Type Variables

Visual Basic programmers must remember that C# is case sensitive. These data types
must be declared in all lower case.
C++ versus C# Data Types
Because C++ is machine dependant and the use of sizeof is required to find out the
range and size of a fundamental data type, the chart below will not always be accurate.
For example an int in C++ may be 16 bits or 32 bits. In C# it is always 32 bits.
C++

C#

bool
char
short
int
long
float
double
unsigned short
unsigned int
unsigned long

bool
char
short
short or int
int or long
float
double
ushort
uint
ulong

Relationship
more restrictive
different size (8 bit vs. 16 bit)
identical

identical
identical
different name
different name

Java versus C# Data Types


Java programmers will recognize 7 of these (byte, short, int, long , float , and
double). These are all identical to Java except for byte. The byte data type is not the
same as Java because it is unsigned in C#. That means that the range of a byte in C# is
always positive from 0 to 255. The C# sbyte is equivalent to the Java byte. The Java
boolean is identical to the C# bool type.
Java

C#

boolean
byte
short
int
long
char
float
double

bool
sbyte
short
int
long
char
float
double

C# Programming (Courseware #10010B)


64

Relationship
different name
different name
identical
identical
identical
identical
identical
identical

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Value Types Storage


int x = 5;
int y = x; // copy

y ++;

6
y
y is affected
n x and y stored directly on the stack
n Fast, less memory required than objects

n Only

C# Programming - Data Types and Value Type Variables

Slide 10

copyright 2001 - Third Millennium, LLP

Value Types and Storage


What is important to note here is that the code y = x copies the data. Later on in the
next module we will look at object references where y = x will not copy the data but
rather only copy the reference to the data.
Declaring two variables of value type allocates separate memory to store the data for both
variables. These two variables remain independent of each other. This is not the case
with reference variables.
The ++ operator will be familiar to Java and C++ programmers, but foreign to VB
programmers. Basically it is equivalent to:
y = y + 1;
Note that the x and y variables will only be stored on the stack if they are declared as
local variables.

example files:
mod02_value\value.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


65

Module #2: Data Types and Value Type Variables

The bool Value Type


bool success = false; // declare
// and assign
success = true; // assign
if (success)
{
// do something
}
C# Programming - Data Types and Value Type Variables

Slide 11

copyright 2001 - Third Millennium, LLP

The bool Value Type


The bool type can not be cast to or from any other simple type. There are only two
possible values: true and false.
Unlike in VB6 and C++ you may not assign numbers to a bool type.

example files:
mod02_value\bool.cs

C# Programming (Courseware #10010B)


66

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Signed Integral Value Types


sbyte max = +127;
sbyte min = -128;

positive and negative


values allowed

short x = -5;
int y = 200123;
long z = x * y;

C# Programming - Data Types and Value Type Variables

Slide 12

copyright 2001 - Third Millennium, LLP

Signed Integral Value Types


Signed integrals can store an equal range of negative and positive values if you consider
zero to be a positive value. Example sbyte has 128 possible negative values -128 to -1
and 128 positive values 0 to 127.
A chart of the different types and their value ranges can be found on page Error!
Bookmark not defined..
short, int, and long are CLS compliant types
sbyte is not CLS compliant

example files:
mod02_value\signed.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


67

Module #2: Data Types and Value Type Variables

Unsigned Integral Value Types


(positive numbers only)
byte max = 255;
byte min = 0;

only positive numbers are allowed

ushort x = 64000;
char letter = 'A'; // character 65
uint y = letter; // y = 65
ulong z = x * y;
C# Programming - Data Types and Value Type Variables

Slide 13

copyright 2001 - Third Millennium, LLP

Unsigned Integral Value Types


char and byte are CLS compliant
ushort, uint, and ulong are not CLS compliant types
The char type may be familiar to those who know ASCII. The ASCII character 65 is the
capital letter A.
In fact char is a Unicode character.

example files:
mod02_value\unsigned.cs

C# Programming (Courseware #10010B)


68

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

The char Value Type


n Unicode

characters (16 bit)


n 65536 characters (0 to 65535) enough to
cover almost all of the worlds alphabets
n If high 9 bits are zero then low 7 bits are the
printable equivalent to the ASCII character
char letter = 'A';
char international = '\u01C0';
char tab = '\t';
C# Programming - Data Types and Value Type Variables

Slide 14

copyright 2001 - Third Millennium, LLP

The char Value Type


Unicode has become the international standard character set. ASCII is a seven bit
character (128 characters) and is often extended using the 8th bit for local character sets
to allow accents and other characters outside the 26 letter US-English alphabet.
Many standard character sets exist world-wide to cover Russian, Japanese, French, Hindi,
and Chinese. Unicode allows for one character set to replace the many different
character sets.
Visit http://www.unicode.org to see the characters that are currently supported, those
that are partially supported, and those that are on the recommendation list to be added.
Currently, over 95% of the worlds written languages are supported.
For example the letter \u01C0 is "c" in Zulu orthography

example files:
mod02_value\char.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


69

Module #2: Data Types and Value Type Variables

Floating Point Value Types


floating point literals default to
double type without the F or M
float small = 0.000001F;
at the end of the literal value
double big = 1.234E+200;
decimal balance = 2000.50m;

n
n

float, double, and decimal are CLS data types


decimal is ideal for currency values

C# Programming - Data Types and Value Type Variables

Slide 15

copyright 2001 - Third Millennium, LLP

Floating Point Value Types


The float type is used for single precision values.
The double type is used for double precision values.
The decimal type is used for floating point numbers that do not loose precision when
using arithmetic. This is a common problem with IEEE standard floating point storage
types due to the complexity of binary conversion. The decimal type should be used for
currency and monetary values.
example files:
mod02_value\float.cs

C# Programming (Courseware #10010B)


70

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Literals
n bool

has only two literals

bool literals: true, false


n Whole

numbers are treated as int literals

int literals: -1, 0, 1, 2, 3...


n Fractional

numbers are treated as double


literals and are never implicitly cast to float
double literals: -1.1, -0.0001, 0.0, 1000.1

C# Programming - Data Types and Value Type Variables

Slide 16

copyright 2001 - Third Millennium, LLP

Literals
There are only two valid literals Boolean values: true and false. Since these are
reserved words they must be all lower case.
Whole numbers are automatically evaluated as int type data except when you assign it to
a smaller data type or use a suffix such as L for long.
Fractional literal numbers (expressed with a decimal point) or numbers expressed in
scientific notation, are evaluated as double type data.
Examples of scientific no tation will be shown later.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


71

Module #2: Data Types and Value Type Variables

Literal Suffixes
nM

for decimal (money)

decimal price = 9.99M;


nD

for double
n F for float
float pi = 3.14f;
nL

for long (use uppercase)


n U for unsigned
ulong trillion = 1000000000000UL;
C# Programming - Data Types and Value Type Variables

Slide 17

copyright 2001 - Third Millennium, LLP

Literal Suffixes
Literal suffixes are not case-sensitive.
Although it is legal to use a lower case L for the literal long suffix, do not use it. Lower
case L looks very similar to the number one. The example below looks like the literal
one thousand and one, but it is actually one hundred with a lower case "L".
long badPractice = 100l;

// one hundred (but looks like 1001)

example files:
mod02_value\suffix.cs

C# Programming (Courseware #10010B)


72

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Hex and Scientific Literals


n Hexadecimal

prefix uses "0x" (zero x)


n Integral types can store hex literals
int rgb = 0xFF33AA;
byte max = 0xFF;

n Real

types can use scientific notation


literals
n E represents "times ten to the power of"
double big = 10e9; // 10 billion
double small = 3E-12; // 0.000000000003
C# Programming - Data Types and Value Type Variables

Slide 18

copyright 2001 - Third Millennium, LLP

Hexadecimal and Scientific Literals


Hexadecimal literals default to int types but can be assigned to smaller integral types.
The compiler checks the high bytes to make sure it is a valid assignment.
Scientific notation literals default to double type. Yo u may not assign a scientific literal
to any other type without casting or using the appropriate suffix.
double x = 5e3;
Cosole.WriteLine(x.ToString());
// 5000 is printed

Another example:
float y = 5e3; // compile error
float y = 5e3f; // ok

example files:
mod02_value\hex.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


73

Module #2: Data Types and Value Type Variables

Size of Value Types


8 bits: sbyte, byte
16 bits: short, ushort, char
32 bits: int, uint, float
64 bits: long, ulong, double
96 bits: decimal

C# Programming - Data Types and Value Type Variables

Slide 19

copyright 2001 - Third Millennium, LLP

Size of Value Types


The size (and thus the range of values possible) in C# fundamental types are fixed. This
solves a common problem that C++ programmers must tackle when porting software
from one machine to another. In C++ the size of each data type often depends on the
machine. For example 16 bit machines like Windows 3.1 used 16 bits to store an int. 32
bit machines like Windows 9x and NT used 32 bits. And 64 bit machines will again
present an issue.
Chart of Value Ranges
type
byte
ushort
char
uint
ulong
sbyte
short
int
long
type
float
double
decimal

min
0
0
0
0
0
-128
-32768
-2,147,483,648
-9,223,372,036,854,775,808
smallest non zero
1.5 10-45
5.0 10-324
1.0 10-28

C# Programming (Courseware #10010B)


74

max
255
65,535
65,535
4,294,967,295
18,446,744,073,709,551,615
127
32767
2,147,483,647
9,223,372,036,854,775,807

max
3.4 1038
1.7 10308
7.9 1028

precision
7 digits
15-16 digits
28-29 digits

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Value Types Conversion


n When

primitive values are converted from


smaller range to bigger range storage types
the conversion is implicit
n When primitive values are converted to data
types where information can be severely
distorted or lost, casting is required

C# Programming - Data Types and Value Type Variables

Slide 20

copyright 2001 - Third Millennium, LLP

For integrals (sbyte, byte, short, ushort, char, int, uint, long, and ulong)
which store only whole numbers, the range can be determined by raising 2 to the power
of the number of bits. For real numbers (float, double, decimal ) the range is based
on an internal storage formula that uses an exponent and mantissa to convert a real
number to binary. Note that real numbers always have the possibility of loss of accuracy
do to the translation to binary. This is a common problem in many languages. The
decimal type avoids this problem by storing the number as a 96 bit binary integer and
using the remaining 32 bits to store the location of the decimal point. That is why
decimals are in fact 128 bit data types but have a range similar to float which is only 32
bits. The decimal type is important for monetary data and other data which can not
loose precision. You can see IBM's web site for more information about the problem
with Java's float and double types and even the Java's java.math.BigDecimal class.
IBM has a BigDecimal class called com.ibm.math.BigDecimal available at
http://www.alphaworks.ibm.com which solves this problem.

Value Types Conversion


Note that conversion from long to double or the conversion from int, uint, and long
to float can cause minor loss of information precision, but never of information
magnitude therefore casting is not required.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


75

Module #2: Data Types and Value Type Variables

Implicit Conversion
conversion from any type
to any other type that
requires going against the
arrows requires a cast

sbyte 8

short 16
byte 8

object

double 64

decimal 128
int 32

ushort 16

float 32

long 64
uint 32

ulong 64

char 16
C# Programming - Data Types and Value Type Variables

Slide 21

copyright 2001 - Third Millennium, LLP

Implicit Conversion
Notice bool is absent. You may not cast to or from any of the above simple value types
to a bool type. Notice object is not a simple value type but in fact a reference type.
Any time you must traverse against the arrows during a conversion, casting is required.
sbyte small = 123;
int bigger = small;
sbyte small = 123;
uint bigger = small;

//ok

// error, if small had been negative,


// uint could not store a negative

C# Programming (Courseware #10010B)


76

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Casting
binary representation

sbyte a = -1;
a 11111111
int x = a;
11111111111111111111111111111111
x
Console.WriteLine(x); // output -1
sbyte b = (sbyte)x; //cast
b 11111111
Console.WriteLine(b); // output -1
byte c = (byte)b; //cast!!
c 11111111
Console.WriteLine(c); // output 255
C# Programming - Data Types and Value Type Variables

Slide 22

copyright 2001 - Third Millennium, LLP

Casting
In C#, an sbyte stores 8 bits using two's complement. That means that the number zero
is stored in binary as 8 unset bits (00000000). The number one is stored as seven unset
bits and one set bit (00000001), but the number negative one is stored as eight set bits
(11111111). The first bit tells the system if the number is positive (0) or negative (1).
The range of an sbyte is -128 to 127. The range of an int is approximately negative 2
billion to positive 2 billion. But since a byte is unsigned, it can not store negative
numbers (no negative sign). For this reason, the range of a byte is 0 to 255.
When you implicitly convert an sbyte to an int, no information can be lost. The
number one stored is converted from 8 set bits to 32 set bits (still the number negative
one). When the number is cast from an int to a byte, the top 24 bits are cut off. Now
we have only 8 set bits left, but byte along with the other unsigned types do not use
two's complement, so the number is valued as the biggest byte which is the number 255.
So be careful when casting numbers.
example files:
mod02_value\cast.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


77

Module #2: Data Types and Value Type Variables

User-Defined Structures (structs)


Value Types
public struct MyPoint
{
public int X;
public int Y;
}
p.X
...
p.Y
MyPoint p;
p.X = 5;
p.X
p.Y
p.Y = 8;

on the stack

n/i
n/i
5
8

C# Programming - Data Types and Value Type Variables

Slide 23

copyright 2001 - Third Millennium, LLP

User-Defined Structures (structs) Value Types


Notice with struct, the new keyword is not required to assign storage for the data.
The following declaration creates enough memory on the stack to store the value of X and
Y, although the value of X and Y remain "not initialized" (n/i).
MyPoint p;

The following statements initialize and set the values of X and Y:


p.X = 5;
p.Y = 8;

The values X and Y must be initialized before they are used. This can be done in one of
three ways.
1. Explicitly assigning the values as demonstrated above.
2. Using a default constructor call with new:
MyPoint p = new MyPoint(); // X and Y are initialized to 0 (zero)
Console.WriteLine(p.X); // prints 0
example files:
mod02_value\struct.cs

C# Programming (Courseware #10010B)


78

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

3. Writing a constructor that takes initial parameter values and assigning them in the
constructor, then using the appropriate call with new. This is very similar to class
constructors and will be covered later in more detail.
public struct MyPoint {
public MyPoint(int x, int y) {
X = x;
Y = y;
}
public int X;
public int Y;
}

MyPoint p = new MyPoint(5,8);


Console.WriteLine(p.X); // prints 5

C# Built-In Types to .NET Framework struct Mapping


The .NET Framework has structs that map to all of C#'s built- in data types. Here is a
chart that shows the mapping:

type

.NET Framework struct

bool
sbyte
short
int
long
byte
ushort
uint
ulong
char
float
double
decimal

System.Boolean
System.SByte
System.Int16
System.Int32
System.Int64
System.Byte
System.UInt16
System.UInt32
System.UInt64
System.Char
System.Single
System.Double
System.Decimal

example files:
mod02_value\struct2.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


79

Module #2: Data Types and Value Type Variables

.NET Framework Structs


using System;
...
DateTime hireDate;

hireDate

n/i

hireDate= new DateTime(1999,12,31);


hireDate

C# Programming - Data Types and Value Type Variables

1999
12
31
Slide 24

copyright 2001 - Third Millennium, LLP

.NET Framework Structs


Notice that the declaration of hireDate reserves enough memory on the stack to store
the entire data structure, but leaves the values un-initialized.
DateTime hireDate;

The assignment operator (=) is used to assign a value to the data and initialize the
variable. This assignment does not create any new objects on the heap. The assignment
simply calls a struct constructor. Constructors are covered later.
hireDate= new DateTime(1999,12,31);

example files:
mod02_value\datetime.cs

C# Programming (Courseware #10010B)


80

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Enumeration Value Types


n
n

Values default to int constants


First constant defaults to 0, then 1, 2

enum Suit
{
Hearts, Clubs, Diamonds, Spades
}
...
Suit card = Suit.Diamonds;
Console.WriteLine(card); // prints Diamonds
Console.WriteLine((int)card); // prints 2
C# Programming - Data Types and Value Type Variables

Slide 25

copyright 2001 - Third Millennium, LLP

Enumeration Value Types


The following enum declaration is equivalent to the one above except that the values
have been explicitly defined:
enum Suit
{
Hearts=0, Clubs=1, Diamonds=2, Spades=3
}

Note, the first Console.WriteLine line above prints "Diamonds" because the
WriteLine method calls the types ToString method which in the case of an enum type
results in the element's name being displayed instead of the enum's value. When cast to
an int type, we see the element's value of 2 being displayed.
More detail on enum types is discussed in a later module.

example files:
mod02_value\enum.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


81

Module #2: Data Types and Value Type Variables

Initializing Value Types


A value type must be definitely assigned before
its value can be obtained

int x;
int y = x; // error
int x;
x = 5;
// definite assignment
int y = x; // ok

Assigned value types must store a valid value


Value types may not store null

n
n

C# Programming - Data Types and Value Type Variables

Slide 26

copyright 2001 - Third Millennium, LLP

Initializzing Value Types


Value types must be definitely assigned before you can use it in another non-assignment
expression. Value types must store valid numbers or values that are within their range.
int x;
int y = x;

// error

The reason the above expression fails to compile is that the value of x was never
initialized. This is only a problem when you are creating local variables. Local variables
are declared in a method, property accessor, indexer accessor, or a constructor. Instance
and static variables belong to objects and classes respectively. These variables are
automatically initialized when the object is instantiated for instance variables or when the
class is loaded for static variables.
You can not assign the null value to a value type. The null value is only available to
reference types.

C# Programming (Courseware #10010B)


82

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #2: Data Types and Value Type Variables

Module 2 Review
Data Types and Value Type Variables

n Variables

must be declared with a specific


type before you can use them
n C# has two data type categories
Value type (bool, char, and numeric types)
Reference type (string, object)
n C#

has 15 built-in types, 11 of which are


CLS compliant, and many more in the .NET
Framework such as DateTime

C# Programming - Data Types and Value Type Variables

Slide 27

copyright 2001 - Third Millennium, LLP

Module 2 Review
In this module, we learned the difference between value types and reference types.
We also went into detailed coverage of the built- in value types and were introduced to
enum and struct types.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


83

Module #2: Data Types and Value Type Variables

Lab Exercise 2
(on your own)
n

Write a program that declares 3 ints and assigns


different values to each. declare 1 long and
assign the values of each int to the long. Use
addition for the second and third. Print the
results.
Write a program that declares 2 DateTime structs.
Assign the first one to today's date. Assign the
second one to the value of the first one. Change
the first one and see if it affects the second.
C# Programming - Data Types and Value Type Variables

Slide 28

copyright 2001 - Third Millennium, LLP

Lab Exercise 2
Part One:
Step #1: Write a program that declares three int type variables. You can name those
variables var1, var2, and var3. Assign a different value to each variable such as 1000,
2000, and 3000.
Step #2: Create a third variable of long type. You can call that variable var4. Assign
var1 to var4. Add var2 to var4. Add var3 to var4. Print the result.
Step #3: What would happen if you tried to assign var4 to any of the int type variables?
Such as:
var2 = var4;

If you are not sure of the result, try it. Even if you are sure, try it to prove your
assumptions. If it fails, fix it.
Part Two:
Step #1: Write a program that declares two DateTime variables:
DateTime first;
DateTime second;

Step #2: Once you have declared both variables, assign the first variable today's date and
the second variable should be assigned to the value of the first.
first = DateTime.Now;
second = first;

Step #3: Print both. Change the first variable and reprint both. Change the first using:
first = first.AddDays(100);
C# Programming (Courseware #10010B)
84

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Module 3
Reference Type Variables

C# Programming

Module 3: Reference Type Variables

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


85

Module #3: Reference Type Variables

Module 3 Topics
Reference Type Variables

n Compare

reference types to value types


n The null reference
n Understand boxing and unboxing
n The string and object types
n Introduction to .NET Framework classes
and user defined classes
n Introduction to arrays, interfaces, and
delegates
C# Programming - Reference Type Variables

Slide 2

copyright 2001 - Third Millennium, LLP

Module 3 Topics
In this module, we will understand reference types compared to value types.
The null reference is an important value fo r enabling garbage collection.
We will understand the process of boxing and unboxing value types in an object
reference.
The string and object types are important built- in types. We will cover some of the
basics of these types.
We will be introduced to the .NET Framework classes such as StringBuilder and Stack.
We will also look at user defined classes.
Finally, we will look at arrays, interfaces, and delegate reference types.
This module will give you a good overall picture of the scope of reference types available
in C#.

C# Programming (Courseware #10010B)


86

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Reference Types
n

C# fundamental class types:


object and string
.NET Framework class types:
System.Random
System.Collections.Stack

User defined class types:


Minimial
Car
Employee
C# Programming - Reference Type Variables

Slide 3

copyright 2001 - Third Millennium, LLP

Reference Types
The object type is an alias for the System.Object class found in the .NET
Framework.
The string type is an alias for the System.String class found in the .NET
Framework.
The object and string types are the two reference types built- in to the C# language. The
remaining reference types can either be found in the .NET Framework or are user-defined.
Classes are used in C# to describe a type of "thing" or type of object. When you create
an instance of a class, you create an object. All reference variables "point-to" an instance
of a class. Class types are not the only type of variable types, though. You can have
delegates, events (which are delegates), interfaces, and array reference types, but all of
these types refer to objects instantiated from classes. The System.Array and
System.Delegate classes are instantiated at run time when you use C# array
references and delegates.
Variables in C# are used to access objects by reference. A reference is not a pointer like
C++, instead it is much safer like Java.
When you declare a variable of value type, C# allocates enough memory on the stack to
store the whole data structure. But when you declare a variable of reference type, C#
only allocates enough memory on the stack to store the reference to a potential object.
Not until you initialize the reference with a new object, will memory on the heap be
allocated to store the whole class data structure.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


87

Module #3: Reference Type Variables

The object Reference Type


n Can

reference anything!

object
object
object
object

obj1
obj2
obj3
obj4

=
=
=
=

true;
// bool
255;
// int
"hello"; // string
new Employee();

n Must

use casting to restore full


functionality of the inherent data type

string message = (string)obj3;


C# Programming - Reference Type Variables

Slide 4

copyright 2001 - Third Millennium, LLP

The object Reference Type


The object type can store anything. Value types are boxed, reference types are simply
reference copies.
To restore a value type, you must unbox it with a cast to the appropriate data type. To
restore a reference type, you must also cast it to the proper type. You may not cast to an
incompatible type or the system will throw an exception.

example files:
mod03_reference\object.cs

C# Programming (Courseware #10010B)


88

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Reference Types Storage


object x = 5;
object y = x;

stack

ref

ref

heap

n Data

stored on the heap


n Assignment copies references not the data
New variable "points to" original object
n Placing

value types in an object is called

boxing
C# Programming - Reference Type Variables

Slide 5

copyright 2001 - Third Millennium, LLP

Reference Types Storage


Objects, unlike structs, enums, and simple value types, are stored on the heap, not on the
stack. Reference types are simply that, a reference only. There is no data on the stack
when you use a reference type. The reference itself is on the stack.
A reference "points to" the data on the heap. The reference is not a pointer and you can
not use pointer arithmetic on a reference.
C# does allow for the creation of inline unsafe code. When you mark a block with the
unsafe modifier, you may use C style pointers and pointer arithmetic.
When you use the assignment operator on a reference, you copy only the reference not
the data. This is different when you have structs and simple value types. The assignment
operator on value types copies all of the data on the stack from one variable to another.
Because references are object-oriented, they require more memory and CPU cycles to
manipulate than stuct types. The overhead is due to features such as garbage collection,
polymorphism, inheritance, and virtual method invocation.
Boxing is covered later in this module.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


89

Module #3: Reference Type Variables

The null Value


object x = 5;
object y = x;

x = null;

y = null;

ref

ref

null

ref

null

null

C# Programming - Reference Type Variables

5
Slide 6

copyright 2001 - Third Millennium, LLP

The null Value


The null value allows an object to refer to "nothing".
Once an object has no references to it, it becomes a candidate for garbage collection.

Garbage Collection
Garbage collection is carried out by the runtime to free memory left from unreachable
objects in memory. The .NET Runtime (Common Language Runtime or CLR) uses a
background thread to check for instances that have gone out of scope, that were
abandoned by a null reference, or are unreachable for any reason from the code running
on the system. By using garbage collection, C# relieves the programmer from the
responsibility of tracking memory allocations and de-allocations. C++ programmers
often spend a good amount of their effort managing memory and avoiding memory leaks
instead of solving business domain problems.

example files:
mod03_reference\null.cs

C# Programming (Courseware #10010B)


90

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Value/Reference
Storage Comparison
stack

int x = 5;
object y = 5;
n
n
n
n

ref

heap

x value stored directly on the stack


y reference is stored on the stack
Object (data) y refers to is stored on the heap
Reference types require more memory and
overhead and thus are slower than value types
C# Programming - Reference Type Variables

Slide 7

copyright 2001 - Third Millennium, LLP

Value/Reference Storage Comparison


The number 5 can be stored directly on the stack, or removed from direct manipulation
by boxing it in an object. The chart above shows two lines of code and demonstrates the
significant difference between the two.
It is important to remember that with references you have two pieces of data, the data
itself and the reference value that refers to the data. You can think of this in terms of an
analogy to money. If you have 5 dollars cash in your pocket, you have direct access to
the 5 dollars. Think of your pocket as the container or variable holding the value. If you
have a bank-debit card in your pocket and your 5 dollars are in the bank, you now have
two things to keep track of: he debit card which refers to the cash in the bank, and the
value of the money in the bank.
Cash in your pocket might be better for certain situations, but a bank account is better for
more sophisticated problems. Simultaneously, cash can be deposited and withdrawn
from a bank account from different sources such as a spouse, your employer, automatic
bill payment. You have the reference to the money when you need it. A value type, like
cash in your pocket, is immediate but not nearly as flexible or powerful as the bank
account.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


91

Module #3: Reference Type Variables

Object References
StringBuilder sb, greeting;
sb = new StringBuilder("hello");
greeting = sb;
sb

ref

greeting

ref

: StringBuilder
text = "hello"
Append(more text)

sb.Append(" world");

: StringBuilder
sb

ref

text = "hello world"

greeting

ref

Append(more text)

C# Programming - Reference Type Variables

Slide 8

copyright 2001 - Third Millennium, LLP

Object References
Because references point to the data and are not the data itself, when you copy a
reference you do not make a copy of the data. When one of the references' data is
manipulated, the other is affected because they point to the same "thing".
StringBuilder sb = new StringBuilder("hello");
StringBuilder greeting = sb;
sb.Append(" world");
// sb is now "hello world"
// greeting is now also "hello world"

Notice in the example above, the variable sb was appended to, but the variable
greeting was also affected. Remember that value data types are not affected when a
copied variable is manipulated:
int x = 5;
int y = x;
y ++;
// x is still 5
// but y is now 6

example files:
mod03_reference\stringbuilder.cs

C# Programming (Courseware #10010B)


92

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Boxing and Unboxing


int w = 4;

ref

ref

object x = w;
int y = (int)x;
object z = x;

boxing
unboxing

// boxing
// unboxing
// not boxing!

Why is the last assignment not boxing?


C# Programming - Reference Type Variables

Slide 9

copyright 2001 - Third Millennium, LLP

Boxing and Unboxing


Boxing is the conversion of a primitive value to an object reference that "boxes" or wraps
the value. Think of a box as a wrapper for a value type.
Unboxing is the conversion of a "boxed" or wrapped value back to a usable value.
Notice that boxing happens implicitly:
object x = w;

Notice that unboxing happens explicitly via casting:


int y = (int)x;

Notice that copying a boxed value does not copy the data, only the reference to the data:
object z = x;

Question: Why is the last assignment not boxing?


Answer: Because the last assignment is copying one reference to another. There is no
conversion of a value type to a reference type since this was already done.

example files:
mod03_reference\boxing.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


93

Module #3: Reference Type Variables

The string Reference Type


string greeting = "Hello ";
greeting

:String
"Hello "

string name;
name n/i (not initialized)
name = "George Washington";
name

:String
"George Washington"

string message = greeting + name;


message

:String
"Hello George Washington"

C# Programming - Reference Type Variables

Slide 10

copyright 2001 - Third Millennium, LLP

The string Reference Type


Strings can be created using double quoted sequences of characters (any Unicode
character).
Declaring a variable as string type only reserves space on the stack for a future
reference to a string object.
string name;

At this point, the name variable is not null, nor does it reference a string. The name
variable is not initialized.
Assigning a value to the variable name creates the object that contains the sequence of
characters. In fact literal strings objects in your code are instantiated when the code is
loaded, before this code is reached and stored in a string pool. When this code is reached,
the reference assignment then points to the previously created object. This behavior is
not guaranteed, and another .NET implementation may create strings on the fly.
name = "George Washington";

Use the plus sign (+) to concatenate strings together:


string message = greeting + name;
example files:
mod03_reference\string.cs

C# Programming (Courseware #10010B)


94

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Reference Types from the


.NET Framework Class Library
using System.Collections;
...
Stack s = new Stack();
s.Push(5);
s.Push(7);
int i = (int)s.Pop();

C# Programming - Reference Type Variables

Slide 11

copyright 2001 - Third Millennium, LLP

Reference Types from the .NET Framework Class Library


This is a quick example of one of the many reference class types. Later we will get into
more details using the collection classes such as the Stack class.
This example shows how the Stack class can be created on the heap to be used to store
data using the Push method. That data can be retrieved later using the Pop method.
Since Pop returns an object not an int, we have to unbox it.

example files:
mod03_reference\stack .cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


95

Module #3: Reference Type Variables

User Defined Classes


class Employee
{
public string Name;
public int EmpId;
}
...
e
Employee e;
e = new Employee();
e

ref

e.Name = "John Doe";


e.EmpId = 1234;

ref

C# Programming - Reference Type Variables

n/i

:Employee
name null
empId
0
:Employee
name John Doe
empId 1234
Slide 12

copyright 2001 - Third Millennium, LLP

User Defined Classes


The following is a class declaration which describes the class data structure. Notice it is
very similar to a struct. The differences between struct and class will be covered in later
modules.
public class Employee
{
public string Name;
public int EmpId;
}

The following is a reference declaration. The variable e can in the future reference
(point) to an object (instance) or null (nothing).
Employee e;

The following is a reference assignment to a new instance (newly created object). At this
point the data structure is created on the heap and can be assigned attribute values.
e = new Employee();

The following code are object field assignments which store data in the object on the
heap.
e.Name = "John Doe";
e.EmpId = 1234;
example files: mod03_reference\employee.cs
C# Programming (Courseware #10010B)
96

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Array Reference Types


int[] data = new int[10];
data[0] = 999;
data[1] = 789;
data
data[2] = 824;
...
data[9] = 1021;

ref

0 999
1 789
2 824
...
9 1021

foreach (int item in data)


{
Console.WriteLine(item);
}
C# Programming - Reference Type Variables

Slide 13

copyright 2001 - Third Millennium, LLP

Array Reference Types


This is an example of the array reference type. The object is instantiated on the heap
using the new operator. Data is assigned to the object (array) using a common array
syntax.
The important observation to make is that all of the information is encapsulated in an
object on the heap. The variable data is just a reference to that object.
The foreach loop retrieves the information one element at a time and places it in a
value type int variable on the stack called item. The int value is then printed.

example files:
mod03_reference\array.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


97

Module #3: Reference Type Variables

Interface Reference Types


n Use

to reference an object of class type


n Can reference many different types of
objects, as long as they share the same
interface
IPerson
IPerson
IPerson
IPerson

person1
person2
person3
person4

=
=
=
=

new
new
new
new

C# Programming - Reference Type Variables

Employee();
Contractor();
TempEmployee();
BoardMember();

Slide 14

copyright 2001 - Third Millennium, LLP

Interface Reference Types


The interface type is used to refer to objects instantiated from different classes that share
the same interface.
The variables person1, person2, person3, and person4 , are references to data on
the heap. The main purpose of an interface reference is to allow polymorphism.
Polymorphism (which means many forms) is a powerful object-oriented feature. Here
we can see four very different types of objects being created. Since they are all comply
to the IPerson interface, we can hold many different forms by using a reference of a
different form.
example files:
mod03_reference\interface.cs

C# Programming (Courseware #10010B)


98

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Delegate Reference Types


n Safe

function pointer
n Used by threads and events
n Example
ThreadStart starter = new ThreadStart(MyMethod);
...
public static void MyMethod()
{
// do something in a separate thread
}

C# Programming - Reference Type Variables

Slide 15

copyright 2001 - Third Millennium, LLP

Delegate Reference Types


Delegate references refer to methods. Actually delegate references refer to an instance of
a subclass of System.Delegate. Here the object is created using the new operator
being applied to the ThreadStart constructor. Conceptually we can think of starter
as a reference to a method.
This example demonstrates how delegate references are similar to class references and
are initialized in the same way using the new operator.
example files:
mod03_reference\array.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


99

Module #3: Reference Type Variables

Module 3 Review
Reference Type Variables
n
n

n
n
n
n
n

The string and object are examples of reference types


Reference types keep a reference variable on the stack
but the data is stored on the heap whereas value types
are stored on the stack
The null reference is used when you have nothing on the
heap to reference but still need the variable for later
Boxing and unboxing is used to hold value types on the
heap using a generic object reference
The .NET Framework contains many classes that
reference types
User defined classes allows for custom reference types
Arrays, interfaces, and delegates are also reference types
C# Programming - Reference Type Variables

Slide 16

copyright 2001 - Third Millennium, LLP

Module 3 Review
In this module we looked at the string and object reference types.
We explored garbage collection and the use of the null reference value.
We used boxing and unboxing to use object, a reference type, to refer to value data, and
return the data back again to its original state on the stack.
We looked at an example of a .NET Framework class, the Stack, and how it can be used
to hold data on the heap.
We saw an example of a user defined class type.
Finally we looked at array, interface, and delegate reference types.
This module is an overview of the different reference types we will explore in the rest of
this course.

C# Programming (Courseware #10010B)


100

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #3: Reference Type Variables

Lab Exercise 3
(on your own)
n

n
n
n
n
n

Write your own public Employee class with two public


fields: first name and last name, make sure to use the
appropriate naming convention
Write a test class with a Main method that instantiates
three employees using three reference variables called e1,
e2, and e3
Populate the three employees with different names
Print the first name of each variable
Assign the reference value of e1 to e2 using e2 = e1;
Change e2's first name and reprint the first name of each
variable and observe the result
Can you explain this behavior?
C# Programming - Reference Type Variables

Slide 17

copyright 2001 - Third Millennium, LLP

Lab Exercise 3
Step #1: Using the Employee class we saw earlier as a model, write your own
Employee class. Make sure the two fields are FirstName and LastName and are both
string types.
Step #2: In a separate class called Test, write a Main method that instantiates your
Employee class three times to create three separate objects. Use the references e1, e2,
and e3 to reference them.
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();

Step #3: Populate the three employees with different names.


e1.FirstName = "Fred";
e1.LastName = "Fintstone";
e2.FirstName = "Barney";

...
Step #4: Print the first and last names for e1, e2 and e3.
Step #5: Assign the reference value of e1 to e2 and then change e2's first name.
e2 = e1;
e2.FirstName = "Max";

Step #6: Reprint all three names. Can you explain this behavior?

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


101

Module #4: Strings and Regular Expressions

Module 4
Strings And Regular Expressions

C# Programming

Module 4: Strings and Regular Expressions

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


103

Module #4: Strings and Regular Expressions

Module 4 Topics
Strings and Regular Expressions

n Use

.NET Framework structs to convert


strings to numeric data
n Clean up strings using the Trim method
n Check for equality with strings
n Use the @ symbol to ignore escape
characters
n Use string formatting
n Use simple regular expressions
C# Programming - Strings and Regular Expressions

Slide 2

copyright 2001 - Third Millennium, LLP

Module 4 Topics
This chapter focuses on using strings to convert to other types, clean up strings, special
string methods, and using regular expressions to search strings.
In this chapter, we will use structs, such as System.Byte and System.Int32, to
convert strings to numeric data by invoking their Parse method.
We will clean up strings with the Trim method to eliminate extra white space before and
after the text in a string.
We will use the @ symbol to write literal strings that ignore escape characters and allow
raw whitespace characters such as carriage returns.
We will examine string formatting used in the Console.WriteLine method and learn
how to use formatting special codes.
Finally, we will learn how to write regular expressions and use them in C# programs to
search for patterns in a string

C# Programming (Courseware #10010B)


104

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

String Concatenation
n Use

the plus operator "+"

n Combine

literal strings

string fullname = "John" + " " + "Smith";

n Combine

variable strings

string first = "John";


string last = "Smith";
string sep = " ";
string fullname = first + sep + last;

C# Programming - Strings and Regular Expressions

Slide 3

copyright 2001 - Third Millennium, LLP

String Concatenation
Strings are useful in any language. In C, strings are character arrays. In C# strings are
immutable objects, instances of System.String.
String concatenation is the process of combining two strings to create a third string. The
plus (+) operator is used to activate concatenation. You should not use string
concatenation in a large loop or with large strings because of the wasted memory and
resources that result. You are better off using the StringBuilder class as
demonstrated earlier on page 92.
Here is an example of using StringBuilder:
string first = "John";
string last = "Smith";
string sep = " ";
fullname = first + sep + last;
Console.WriteLine(fullname);
StringBuilder sb = new StringBuilder(first);
StringBuilder full = sb;
sb.Append(sep);
Console.WriteLine(sb);
// sb is now "John Smith"
Console.WriteLine(sb);
// full is now also "John Smith"
Console.WriteLine(full);
example files:
mod04_strings\concat.cs
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


105

Module #4: Strings and Regular Expressions

Converting Strings to Numbers


n
n

The .NET Framework has a struct defined for


every simple type
The Parse Method
There is a static method called Parse in each
simple type's underlying struct that accepts a string
and returns the appropriate simple type
string myText = "123";
int myInt = Int32.Parse(myText);
byte myByte = Byte.Parse(myText);

What would happen if myText was "-123"?


C# Programming - Strings and Regular Expressions

Slide 4

copyright 2001 - Third Millennium, LLP

Converting Strings to Numbers


Simple Type

Underlying Struct

sbyte
byte
short
ushort
int
uint
long
ulong
char
float
double
bool
decimal

System.SByte
System.Byte
System.Int16
System.UInt16
System.Int32
System.UInt32
System.Int64
System.UInt64
System.Char
System.Single
System.Double
System.Boolean
System.Decimal

Question: What would happen if myText was "-123"?


Answer: Int32.Parse(myText) would succeed, but Byte.Parse(myText) would
fail because bytes range is 0 to 255
The failure would generate an OverflowException. We will deal with exception
handling in a later module.
example files:
mod04_strings\convert.cs
mod04_strings\convert_bad.cs

C# Programming (Courseware #10010B)


106

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

Trim, Cleaning Up Strings


n Use Trim() to

remove whitespace from the


beginning and ending of a string
string message = " \t hello world \r\n ";
message = message.Trim();

n Use TrimStart(null)

or TrimEnd(null) to
remove whitespace only from one side
string message = " \t hello world \r\n ";
message = message.TrimEnd(null);
Console.WriteLine("[" + message + "]");

C# Programming - Strings and Regular Expressions

Slide 5

copyright 2001 - Third Millennium, LLP

Trim, Cleaning Up Strings


Trim, TrimStart , and TrimEnd are all instance methods. You must ask the string to

trim itself and receive the new string. In both examples above, the returned value is
reassigned to the original variable. You could assign the trimmed value to a new string
variable if you needed both the original string and the modified string.
example files:
mod04_strings\trim.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


107

Module #4: Strings and Regular Expressions

Checking For Equality


n
n
n

Single equal sign used for assignment " ="


Double equal sign used to test for equality " =="
The == compares the information in the string

string
string
char[]
string
if (s1
if (s1

s1 = "hello";
s2 = "hello";
data = {'h', 'e', 'l', 'l', 'o'};
s3 = new String(data);
== s2) { /* this is true */ }
== s3) { /* this is also true! */ }

C# Programming - Strings and Regular Expressions

Slide 6

copyright 2001 - Third Millennium, LLP

Checking for Equality


The == operator is overloaded in the String class to invoke the .Equals method. That
is why the comparison of two strings checks the value of the data not the value of the
reference.
In C#, the runtime system may use the same string when two variables point to a literal
string containing the same value. This allows for smaller memory footprint. This will
have no detrimental effects because string objects are immutable, they can't be changed.
A string reference variable can point to a new string object making it seem like the string
has changed, but behind the scenes two separate objects will be used.
string s1 = "hello";
string s2 = "hello";
char[] data = {'h', 'e', 'l', 'l', 'o'};
string s3 = new String(data);
The third string, s3, is an explicit instantiation of the String class using a character array.

The runtime system will probably not use the same string but rather create a new instance.
The comparison of s1 and s3 will most probably be comparing two separate instances.
In Java, the second if statement would be false because Java's == operator compares
references, not string data. This can be the cause of many bugs in Java. If you want to
compare two references to see if they point to the same object in memory, use the static
Object.ReferenceEquals method. For example:
if (Object.ReferenceEquals(s1, s3)) {/*this is probably false*/}
example files:
mod04_strings\equality.cs
C# Programming (Courseware #10010B)
108

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

The .Equals Method


n

the string's == operator is overloaded


to use the .Equals method

string s1 = "hello";
string s2 = "hello";
if (s1 == s2) { /* this is true */ }
if (s1.Equals(s2)) { /* also true */ }
C# Programming - Strings and Regular Expressions

Slide 7

copyright 2001 - Third Millennium, LLP

The .Equals Method


The .Equals method is inherited from the Object class and is therefore present in every
data type in C#. The default behavior check to see if two instances are the same instances
in memory. Many classes that represent immutable value- like objects will override it to
compare data, not the reference values. When this is done, the == operator, whose
behavior has the same default behavior as the .Equals method, is overloaded to call the
overridden .Equals method. Later modules will cover the concepts of overloading and
overriding.
At this point it is important that you understand that for certain data types such as strings,
the == and .Equals operation are identical and compare the data in the string not the
memory address (reference value).

example files:
mod04_strings\equality.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


109

Module #4: Strings and Regular Expressions

Escape Sequences
n "\t"

is a tab character

string message = "hello\tworld";

n "\r\n"

are two characters that end a line in a


MSDOS/Windows ASCII text file

string twoLines = "hello\r\nworld\r\n";

n What

does the string "c:\temp\restore.txt"


translate to?

C# Programming - Strings and Regular Expressions

Slide 8

copyright 2001 - Third Millennium, LLP

Escape Sequences
\r
\n
\t
\\
\"

carriage return (think of a typewriter, moves to far left)


new line (moves down)
tab
the backslash character
the double quote character

For example, to print:


She said "hello" to me.

Use the \" escape sequence:


Console.WriteLine("She said \"hello\" to me.");

Question: What does the string "c:\temp\restore.txt" translate to?


Answer: "c:\" tab "emp" carriage return "estore.txt"
The printout on the console might be strange because the carriage return (\r) does not
have a reliable behavior without the new line (\n).
example files:
mod04_strings\escape.cs

C# Programming (Courseware #10010B)


110

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

Ignoring Escape Sequences


n Use

the @ sign in front of a string to ignore


escape sequences
n Use it for literal strings
n Allows for multi-line strings
string filename = null;
filename = @"c:\temp\restore.txt";
string multiline = @"this is a
multi line string";
C# Programming - Strings and Regular Expressions

Slide 9

copyright 2001 - Third Millennium, LLP

Ignoring Escape Sequences


C# uses the at sign (@) prefix in front of literal strings to ignore escape sequences and
incorporate new lines and other literal characters.
The first example of a filename will allow you to enter windows paths without causing
problems mentioned earlier. This symbol is very useful and is commonly used in C#
programs.
The multiline example shows how you can have a literal string that spans two lines (or
more of code.
example files:
mod04_strings\multiline.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


111

Module #4: Strings and Regular Expressions

String formatting
string user = Console.ReadLine();
Console.WriteLine("Welcome {0}.", user);
int qty = 5;
string item = "hats";

string with format holders

Console.WriteLine("I have {0} {1}.", qty, item);


// output: I have 5 hats.

objects to be inserted
into format holders

string output = null;


// remember output for later
output = String.Format("I have {0} {1}.", qty, item);
Console.WriteLine(output);

C# Programming - Strings and Regular Expressions

Slide 10

copyright 2001 - Third Millennium, LLP

String formatting
If you wanted to print formatted output, you can print a format string followed by a list of
variables to insert into the formatted string. Here are two examples:
int red = 255;
int green = 0;
int blue = 204;
Console.WriteLine("<font color='#{0:X2}{1:X2}{2:X2}'>",
red, green, blue );
would print out:
<font color='#FF00CC'>

The place holder {0:X2} has two parts. The left side of the colon indicates which
variable 0, 1, or 2. 0=red, 1=green, 2=blue. The right side of the colon indicates X for
hexadecimal, and 2 for the number of digits. Thus the number 255 becomes the
hexadecimal number "FF", 0 becomes "00" and 204 becomes "CC".
decimal price = 2.05m;
int qty = 6;
decimal total = price * qty;
Console.WriteLine("price={0:C} qty={1} total={2:C}",
price,
qty,
total);

would print out:

price=$2.05 qty=5 total=$12.30

The price and total placeholders include the letter "C" after the colon in the format to
indicate currency. E = Exponential (scientific) notation, F = Fixed point, G = General, P
= Percent. For a full list of formatting codes refer to the .NET Framework documentation.
example files: mod04_strings\formatting.cs
C# Programming (Courseware #10010B)
112

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

Regular Expressions
n

The using statement


using System.Text.RegularExpressions;

The regular expression or pattern to look for


string pattern = "is"; // regular expression

match
n

The match
string input = "This is a test";
bool found = Regex.IsMatch(input, pattern);
if (found) {
Console.WriteLine("match found for '{0}'", pattern);
}
C# Programming - Strings and Regular Expressions

Slide 11

copyright 2001 - Third Millennium, LLP

Regular Expressions
Regular Expressions (regex) are a powerful search mechanism that searches for patterns
in text. The UNIX world has enjoyed regex for years, recently Microsoft incorporated
regex into VBScript and now, in .NET, it is available to all .NET CLI compliant
languages including COBOL and Visual Basic.
In the basic pattern to look for above, the pattern string is two characters i and s. The
input string being searched is "This is a test". Notice that the characters i and s appear in
sequence in two places. The first appearance is in the word "This" and the second is "is".
The result of the IsMatch method is true if it finds the pattern in the search string. If it
does (anywhere) it returns a true. If it is not found, the result is false.
The Regex class and the whole System.Text.RegularExpressions namespace are much
more powerful than this simple example. This example is designed to introduce you to
the topic. O'Reilly and Associates publish a book called Mastering Re gular Expressions
by Jeffrey E. F. Friedl (with an owl on the cover).
In the next few pages we will cover some basic expressions with meta-characters and
qualifiers.
example files:
mod04_strings\regex.cs

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


113

Module #4: Strings and Regular Expressions

Regular Expressions (regex)


n The

expression is a sequence of characters


n The sequence is used to find a match of the
same pattern in another string
If the expression is "abc" then a match would
exist if three letters "a", "b", and "c" appeared in
the same sequence in the search string
The pattern "abc" matches "abababcbcbc"
The pattern "abc" does not match
"ababacbcbc"
C# Programming - Strings and Regular Expressions

Slide 12

copyright 2001 - Third Millennium, LLP

Regular Expressions (regex)


The expression, or pattern, is a sequence of characters to look for in a search string.
If the same pattern in the regular expression (regex) is found in the input string being
searched, the expression is said to "match" the search string. If the pattern is not found
exactly as expressed in the regex, then no match will happen and the match fails.
When using RegEx.IsMatch(input, pattern), if the expression appears multiple times in
the search string, a match returns true when the first match is found. Otherwise the
IsMatch method and its regular expression will return false if no match is found.

C# Programming (Courseware #10010B)


114

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

Regex Meta-Characters
n Characters

in the expression can be metacharacters and quantifiers

char

meaning

example: "regex" matches "search string"

any character

"f..d" matches "I eat food", "fold the paper"

or

"Sam|John Smith" matches "Sam Jones"

()

group

"(Sam|John) Smith" matches "Sam Smith"

zero or more

"fo*d" matches "food", "fd", "fodder"

one or more

"fo+d" matches "food", "fodder"

zero or one

"fo?d" matches "fd", "fodder"

C# Programming - Strings and Regular Expressions

Slide 13

copyright 2001 - Third Millennium, LLP

Regex Meta-Characters
The meta-characters in the chart demonstrate several characters that have special
meaning in a regular expression.
For example the dot (.) character represents any single character, including an alpha,
numeric, punctuation, or even a space character. Two dots (..) represent two of any
character. Therefore the regex "f..d" matches on "food", "fold", "soft drink". Notice in
the "soft drink" search string, the "f" is followed by two characters, a "t" and a space, then
followed by a "d" character.
Sequence is important. The sequence of characters must be exact. If my regex is "f..d",
then I must have one "f" followed by exactly two characters, followed by one "d". What
comes before the "f" and after the "d" is not significant. For example in the search string
"I eat food at lunch" the characters before and after "food" are not important to the
regular expression "f..d".
Quantifiers are meta-characters that determine the quantity of the character or group
before it appears. For example in the expression "fo*d" the star (*) quantifies the
character "o". This expression states that zero or more "o" characters must follow an "f"
and precede a "d" character. Therefore the "fo*d" expression matches the search string "I
eat food at lunch" because there is an "f" followed by zero or more "o" characters
followed by a "d" character. The "fo*d" would fail on the search string "fold the paper"
because the "l" appears between the "o" and the "d". The "fo*d" expression can only
match successfully if the "f", "o", "d" sequence has no other characters in it, even a space
character.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


115

Module #4: Strings and Regular Expressions

Complete Example
using System;
using System.Text.RegularExpressions;
class Test {
static void Main() {
string pattern = "f..d"; // expression
string input = "I eat food for lunch"; // search string
bool found = Regex.IsMatch(input, pattern);
if (found) {
Console.WriteLine("{0} matches {1}", pattern, input);
} else {
Console.WriteLine("{0} fails on {1}", pattern, input);
}
}
}

C# Programming - Strings and Regular Expressions

Slide 14

copyright 2001 - Third Millennium, LLP

Complete Example
This example demonstrates the use of a regular expression with meta characters. If you
edit this file you can change the pattern by retyping it and recompiling.
A better file to experiment with regular expressions is the sample file grepsharp.cs.
This file contains topics that will be covered later and therefore the example code is not
displayed. The grepsharp program takes a pattern and a filename at the command line,
very similar to the Unix grep command. This will allow you to experiment with a file
called search.txt that contains the strings in the chart from the previous page.

example files:
mod04_strings\regex_complete.cs
mod04_strings\grepsharp.cs
mod04_strings\search.txt

C# Programming (Courseware #10010B)


116

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

Module 4 Review
Strings and Regular Expressions
n

n
n
n
n
n

The .NET Frameworks includes structs for each simple


type with a Parse method to convert strings into the
appropriate simple type
You can remove extra whitespace in strings using the
Trim, TrimStart, and TrimEnd methods
You can use either == or .Equals to compare two strings
for equality
Use the @ symbol to ignore escape characters
Use WriteLine or String.Format to provide string
formatting with variables
Use Regex.IsMatch method for simple regular
expressions
C# Programming - Strings and Regular Expressions

Slide 15

copyright 2001 - Third Millennium, LLP

Module 4 Review
In this chapter we looked at string functionality in C# including concatenation vs.
StringBuilder 's Append method.
We also looked the Parse method in each of the simple type structs in order to convert a
string to other simple types like int and byte.
We used Trim, TrimStart, and TrimEnd to clean up strings.
We examined the difference between == and .Equals and how they are often identical,
especially in immutable objects like strings.
We learned a few escape characters such as \\, \t, \n, and \r. We also learned how to use
the @ prefix to ignore escape characters and allow multi- line literal strings.
We learned the built in Format function and how it is also used by the
Console.WriteLine method.
Finally we learned how to use the Regex.IsMatch class to do use regular expressions to
search for patterns in text.

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


117

Module #4: Strings and Regular Expressions

Lab Exercise 4
(on your own)
n
n
n
n
n
n

Create a variable called s1 to store a string that contains a


sentence with the word "sailboat".
Create another variable called s2 to store a string that
contains the word "boot" in it.
Concatenate the two strings, s1 first and s2 second, and
store the result in s3
Use regular expressions to search each variable for the
pattern "bo*t". Which variables match: s1, s2, or s3?
Try the pattern "bo.t". What is the difference between
these two patterns?
Finally try the pattern "boat.*boot".
C# Programming - Strings and Regular Expressions

Slide 16

copyright 2001 - Third Millennium, LLP

Lab Exercise 4
Step #1: Start a C# console project or open a new file in your editor. In the Main method,
use the variables s1, s2, and s3, create three strings. The strings s1 and s2 will contain the
literal strings:
string s1 = "I like to sail in a sailboat. ";
string s2 = "I lost my boot in the water. ";

Step #2: Using string concatenation, create s3 from the contents of s1 and s2. Make sure
that s1 is first and s2 is second.
Step #3: Use regular expressions to search all three strings individually for the pattern
"bo*t". If you find a match display a message stating you found a match for the pattern
and were you found it. Example output:
Found a match for "bo*t" in "I like to sail in a sailboat. "

If you don't find a match the output should display a negative message:
No match found for "bo*t" in "I like to sail in a sailboat. "

The output should be no match for s1 but a match for s2 and s3 because the pattern
"bo*t" searches for the letter "b" followed by zero or more letter "o" characters followed
by the letter "t". Remember, * is not a wildcard, it is a quantifier for zero or more of the
previous item.

C# Programming (Courseware #10010B)


118

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Module #4: Strings and Regular Expressions

Note, only one of the two messages should be displayed by your program for each
variable s1, s2, and s3. If you get both "Found a match..." and "No match found..."
messages for the same variable, make sure you are using an if/else statement.
if (condition)
{
// do something
}
else
{
// do something else
}

Step #4: Make a change to the program to include a search of all three strings for the
pattern "bo.t" and "boat.*boot". To separate each pattern result, add a line before
each pattern group that states something like:
Using pattern: bo*t

Include a carriage return line feed escape sequence to put a blank line in front of the word
"Using".
Note: Because we have not covered writing our own methods and using arrays, this code
may require copy-and-paste programming. Don't worry, we will cover methods and
arrays later. If you feel comfortable enough, you can try to using arrays or methods to
reduce the code required to solve this lab exercise. The solution provided does not
assume any knowledge of arrays of writing methods besides the Main method. Here is
the expected output:

Using pattern: bo*t


No match found for "bo*t" in "I like to sail in a sailboat. "
Found a match for "bo*t" in "I lost my boot in the water. "
Found a match for "bo*t" in "I like to sail in a sailboat. I lost my
boot in the water. "
Using pattern: bo.t
Found a match for "bo.t" in "I like to sail in a sailboat. "
Found a match for "bo.t" in "I lost my boot in the water. "
Found a match for "bo.t" in "I like to sail in a sailboat. I lost my
boot in the water. "
Using pattern: boat.*boot
No match found for "boat.*boot" in "I like to sail in a sailboat. "
No match found for "boat.*boot" in "I lost my boot in the water. "
Found a match for "boat.*boot" in "I like to sail in a sailboat. I lost
my boot in the water. "

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


119

Course Review

Course Review
C# Programming

C# Programming

Course Review

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


463

Course Review

Objectives Review
n Understand

C# Language Fundamentals
n Use .NET objects and classes
n Define custom structs, enums, objects and
classes
n Design classes with properties, methods,
indexers, and events
n Communicate over the internet and web
n Manipulate XML
C# Programming

Slide 2

copyright 2001 - Third Millennium, LLP

Objectives Review
Now that you have completed this course, you should have a good understanding of C#
language fundamentals. With the fundamentals, you can learn any aspect of C#
programming from client-side, Windows GUI, server-side, Web pages using ASP .NET,
and Web services.
We covered using the .NET class library to use classes and object for manipulating files,
retrieving Web pages, using Regular Expressions, and much more.
We defined custom structs, enums, objects and classes.
We designed classes that expose properties, methods, events, and indexers. We stored
those classes in reusable DLL libraries as private and shared assemblies.
We learned how to communicate over the Internet using Uri, Dns, and WebRequest
classes.
Finally we learned how to manipulate XML using DOM objects and serialize our object
to and from XML instances.

C# Programming (Courseware #10010B)


464

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Course Review

What's Next
Depending on your particular use of C# and
.NET you may want to look for more training
aids or courses on the following topics:
n ADO

.NET with C#
n ASP .NET with C#
n Web Services with C#
n Visual Basic .NET
C# Programming

Slide 3

copyright 2001 - Third Millennium, LLP

What's Next
Consider continuing learning on the following topics:
ADO .NET with C#
Learn more about ADO .NET (ActiveX Data Objects) for access to databases such as
Oracle and Microsoft SQL Server using the latest trends in XML.
ASP .NET with C#
Learn more about Web site development with C# and ASP .NET (Active Server Pages).
Web Services with C#
Learn more about XML Web Services using SOAP (Simple Object Access Protocol) and
WSDL (Web Service Description La nguage) to design Web sites that communicate with
other Web sites and the next generation of EDI (Electronic Data Interchange)
Visual Basic .NET
Learn more about the next generation of Visual Basic

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone: (781)674-9720

C# Programming (Courseware #10010B)


465

Course Review

Resources
n

Information for C# and .NET programmers


http://www.thirdm.com/

Microsoft Developer Network


http://msdn.microsoft.com/net/

Visual Studio
http://msdn.microsoft.com/vstudio/

Other
http://www.csharphelp.com/
http://www.csharpindex.com/
C# Programming

Slide 4

copyright 2001 - Third Millennium, LLP

Resources
Information for C# and .NET programmers
Go to the ThirdM.com web site for information about C# and .NET trends.
http://www.thirdm.com
MSDN and Visual Studio
Microsoft's web sites include online articles and documentation on C# and the .NET
framework.
http://msdn.microsoft.com/net
http://msdn.microsoft.com/vstudio
Other Resources
There are plenty of Web sites on the Internet for C# information. You may find the C#
Help and C# Index web sites helpful.
http://www.csharphelp.com
http://www.csharpindex.com

C# Programming (Courseware #10010B)


466

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Index

INDEX
#define, 445
#if, 445
#region, 445
#warning, 445
%, 52
&, 52
&&, 53
.NET Runtime, 66, 96, 245, 351, 413
@, 117
== operator, 114
abstract, 332
abstract class, 332
Access Levels, 272
ActiveX, 419
ActiveX DLL, 413
Application class, 384
Application.Run, 384
ApplicationException, 182, 183
Array class, 204
ArrayList, 220
arrays, 201
declaring, 201
as operator, 321
associative array, 227
Attribute class, 441
attribute targets, 435
Attributes, 433
auto-increment, 55
base, 322
base class, 309
base keyword, 329
bool, 71
Boxing, 99
break, 140
Built-In Types to .NET Framework
struct Mapping, 84
Button, 386, 387
C++, 12, 19, 24, 26, 28, 30, 37, 42, 49,
56, 69, 70, 71, 79, 93, 96, 135, 144,
149, 151, 153, 201, 208, 242, 268, 296,
347, 444
camelCase, 62
case, 132
Casting, 82
Casting references, 318
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

catch blocks, 184


Ceil, 173
char, 74
checked, 186
class, 149, 261
Class Library, 24, 26, 101, 146, 156, 167,
175, 179, 209, 256, 272, 409, 421, 422
Class members, 262
Class vs. Object, 149
classes
common members, 263
CLR, 65
CLS, 19, 65
CLS compliant, 62, 72
CLS Compliant Simple Types, 65
CLSCompliant attribute, 437
COBOL, 19, 28, 30, 65, 120, 208
Collections, 219
common controls, 386
Common Language Runtime, 65
Common Language Specification, 65
compound statement, 50
concatenation, 111
Conditional attribute, 447
const modifier, 280
constructor, 150, 323
continue, 139
Control class, 400
csc, 39
currency, 118
DateTime, 166, 238, 240
DayOfWeek enum, 248
DBNull, 251
decimal, 75
Declaring Variables, 61
delegate, 367
destructors, 153
dictionary, 227
DivideByZeroException, 180
DLL, 413
DLL Hell, 410, 413, 424, 429
Dns clas, 453
do/while loop, 134
double, 75
ECMA, 19
C# Programming (Courseware #10010B)
467

Index

encapsulation, 149
enum
calculated values, 254
user defined, 253
enum types, 247
enumeration, 247
Equals method, 114, 115, 334
event, 397
event handler, 397, 401
EventArgs, 398
EventHandler delegate, 398
events
user defined, 404
exception, 179
Exception
Constructors, 192
Exception Abuse, 179
Exception Handling, 181
when to use, 191
Exceptions
Generating, 193
wrapping, 194
exit code, 43
Explicit initialization, 266
Explicit interface implementation, 351
fields, 155
File class, 172
FileInfo, 167, 179, 220
FileInfo Class, 162
finally, 185
finally block, 185
float, 75
Floor, 173
for loop, 135
foreach loop, 136, 230
with collections, 222
forwarding, 353
function pointer, 367
GAC, 9, 26, 410, 424, 425, 426, 428,
429
garbage collection, 153
Garbage collection, 96
GetElementByTagName, 474
GetEnumerator, 359
GetHashCode, 335
Global Assembly Cache, 424
goto, 139, 141
grep, 123

GUI, 383, 386


GUID, 413
hash, 227
Hashtable, 227, 229
heap, 66
ICollection interface, 223
IDictionary interface, 228
IEnumerable, 359
IEnumerable interface, 228, 230
IEnumerator, 359
if, 130
IL Disassembler, 419
ildasm, 419
IList interface, 224
Implicit Conversion, 81
Initializing Value Types, 87
Inner classes, 276
InnerText property, 473
InnerXml property, 473
Instance Fields, 266
instance variables, 155
interface
purpose, 343
Interface events, 358
Interface Members, 344
interface polymorphism, 347
Interface Properties, 354
internal, 273
internal keyword, 417
internal modifier, 412, 418
internal protected, 275
IPAddress class, 453, 455
IPHostEntry, 453
is operator, 321
jagged array, 214
Java, 19, 27, 28, 37, 49, 57, 63, 69, 70,
80, 93, 114, 132, 135, 148, 149, 151,
153, 166, 191, 201, 203, 237, 240, 247,
268, 275, 290, 296, 299, 325, 347, 412,
413, 415, 418, 419, 433, 478
Java's finalize method, 153
JavaScript, 61
Join, 208
jump statements, 138
key, 227
Keys, 228
Label, 386
Location property, 387

C# Programming (Courseware #10010B)


468

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

logical operators, 129


Logical Short-Circuit And Operator, 53
Main method, 36
MainMenu, 391
MainMenu class, 390
Math class, 173, 174
Max, 173
Member Initialization, 264
MenuItem class, 390
MenuItems property, 391
Message passing, 156
Message Passing, 159
MessageBox, 402
meta-characters, 122
method, 155
Method Overriding, 324
Methods, 156
Min, 173
Modules, 415
modulus operator, 52
MSIL, 415
multicast delegate, 376
multicast delegates, 377
multidimensional array
jagged, 214
Multi-dimensional arrays, 213
multithreaded, 368
Namespace, 411
Namespace vs. Assembly, 417
naming convention, 62
Nested try/catch blocks, 190
netmodule, 415
NonSerialized attribute, 438
Now, 240
null value, 96
object, 94, 149
Object.ReferenceEquals, 337
Operator overloading, 336
Operators, 51
OverflowException, 186
overload operators, 54
override, 328
Commonly Overridden Methods, 333
PascalCase, 62
Perl, 19, 28, 29, 30, 37, 49, 61, 65, 135,
136, 144, 201, 208, 272, 437, 478
Point, 239
Point struct, 387
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720

Polymorphic Methods. See


polymorphism, 324
Polymorphism, 316, 317
Pop method, 225
Preprocessor Directives, 444
private, 273
private data, 268
private inner-class, 276
Properties, 166, 269, 354
veto access, 271
property, 155
protected, 275
protected internal, 275
public, 276
Push method, 225
Queue object, 226
Random class, 158
readonly modifier, 280
Redirecting standard error, 46
redistributable package, 40
reference, 151
Reference types, 63
references, 98
reflection, 375
regex, 120
Regex, 208
Regular Expressions, 120
return, 142
for properties, 269
Round, 173
sbyte, 72
Schema, 476
scientific notation, 76
sealed, 332
SecurityException, 179
semantics, 347
SerializableAttribute, 438
setup, 39
Shared Assembly, 428
simple types, 64
Smalltalk, 65
SOAP, 10, 26, 439, 440, 475, 477, 489
SoapFormatter, 475, 477, 479
specialization, 314
Split, 208, 211
Sqrt, 173
stack, 66
Stack collection, 225
C# Programming (Courseware #10010B)
469

Index

state, 170
State, 265
static, 42
Static fields, 174, 278
Static methods, 170, 171
StreamReader, 163, 459
StreamWriter, 165
String class, 208
String formatting, 118
StringBuilder, 111
strong name, 425
structs, 83
structure, 237
stuct types
constructors, 243
subclass, 311
switch, 132
target, 383
TextBox, 386
this, 322
Thread class, 368
ThreadStart, 368
throw, 143, 193
TicksPerSecond, 241
TimeSpan, 238, 241
Today, 240
ToString method, 333
Trim, 113
try/catch, 181
TypeCode, 251
Unboxing, 99
unchecked, 186
Unicode, 73, 74
Unix, 123
unsafe, 95
URI, 456
Uri class, 457

URL, 456
user-defined type, 237
ValidationEventHandler, 471
value, 269
Value types, 63
Values, 228
VB, 402, See
VB6, 27, 49, 50, 61, 68, 71, 132, 201,
240, 347, 358, 388, 420
VBScript, 61
virtual, 327
Visual Basic, 2, 12, 19, 28, 49, 61, 62,
63, 68, 69, 120, 136, 148, 149, 151,
166, 208, 240, 247, 388
Web service, 439, 440
Web services, 439, 440, 488
WebMethod attribute, 439
WebRequest class, 458
WebResponse, 458
WebService attribute, 439
while loop, 133
winexe, 383
WSDL, 440
XML, 21, 26, 36, 48, 56, 426, 465, 466,
467, 468, 469, 470, 472, 475, 478, 479,
480, 481, 482, 483, 485
XML documentation, 480
XML namespace, 439, 440, 456
XmlDocument, 469, 472
XmlElement, 473
XmlNode, 474
XmlNodeList, 472, 474
XmlReader, 469
XmlSerializer, 475, 476, 479
XmlTextNode, 474
XmlTextReader, 470
XmlValidatingReader, 470

C# Programming (Courseware #10010B)


470

Copyright 2002 Third Millennium, LLP


http://www.thirdm.com - phone (781) 674-9720

Anda mungkin juga menyukai