800 East 96th St., Indianapolis, Indiana, 46240 USA
Bradley L. Jones
the C#
Language
in
21
Days
Teach Yourself
Sams Teach Yourself the C# Language
in 21 Days
Copyright © 2004 by Bradley L. Jones
All rights reserved. No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical, photo-
copying, recording, or otherwise, without written permission from the pub-
lisher. No patent liability is assumed with respect to the use of the information
contained herein. Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from the use of
the information contained herein.
International Standard Book Number: 0-672-32546-2
Library of Congress Catalog Card Number: 2003092624
Printed in the United States of America
First Printing: July 2003
06 05 04 03 4 3 2
Trademarks
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized. Sams Publishing cannot attest to
the accuracy of this information. Use of a term in this book should not be
regarded as affecting the validity of any trademark or service mark.
Warning and Disclaimer
Paula Lowell
TECHNICAL EDITOR
Anand Narayanaswamy
TEAM COORDINATOR
Cindy Teeters
INTERIOR DESIGNER
Gary Adair
COVER DESIGNER
Alan Clements
PAGE LAYOUT
Michelle Mitchell
Contents at a Glance
Introduction 1
Week 1 Week at a Glance 5
DAY 1 Getting Started with C# 7
TYPE & RUN 1 37
2 Understanding C# Programs 41
3 Manipulating Values in Your Programs 83
4 Controlling Your Program’s Flow 117
TYPE & RUN 2 145
5 The Core of C# Programming: Classes 153
6 Packaging Functionality: Class Methods and Member Functions 179
7 Storing More Complex Stuff: Structures, Enumerators, and Arrays 211
Week 1 Week in Review 245
Week 2 Week at a Glance 269
DAY 8 Advanced Method Access 271
9 Handling Problems in Your Programs: Exceptions and Errors 303
TYPE & RUN 3 347
10 Reusing Existing Code with Inheritance 357
11 Formatting and Retrieving Information 395
Creating the Source Code 9
Understanding the Execution of a C# Program 11
Compiling C# Source Code to Intermediate Language 13
Completing the Development Cycle 14
Creating Your First C# Program 16
Entering and Compiling Hello.cs 17
Types of C# Programs 21
Creating Your First Window Application 21
Why C#? 25
C# Is Object-Oriented 26
C# Is Modular 26
C# Will Be Popular 26
A High-Level View of .NET 27
C# and Object-Oriented Programming (OOP) 28
Object-Oriented Concepts 28
Objects and Classes 30
Summary 31
Q&A 32
Workshop 33
Quiz 33
Exercises 34
T
YPE & RUN 1 Numbering Your Listings 37
The First Type & Run 38
C
HAPTER 2 Understanding C# Programs 41
Dissecting a C# Application 42
Starting with Comments 43
Basic Parts of a C# Application 48
Formatting with Whitespace 48
Working with Floating-Point Values 69
Gaining Precision with Decimal 70
Storing Boolean Values 70
Working Checked Versus Unchecked Code 71
Data Types Simpler Than .NET 72
Literals Versus Variables 74
Working with Numeric Literals 74
Working with Boolean Literals (
true and false) 75
Understanding String Literals 76
Creating Constants 76
A Peek at Reference Types 76
Summary 77
Q&A 78
Workshop 79
Quiz 79
Exercises 80
Contents vii
CHAPTER 3 Manipulating Values in Your Programs 83
Displaying Basic Information 84
Displaying Additional Information 85
Manipulating Variable Values with Operators 87
Unary Operator Types 87
Binary Operator Types 88
Ternary Operator Types 88
Understanding Punctuators 88
Moving Values with the Assignment Operator 89
Working with Mathematical/Arithmetic Operators 90
Adding and Subtracting 90
Doing Multiplicative Operations 91
if 118
Discovering the
switch Statement 123
viii Sams Teach Yourself the C# Language in 21 Days
Using Iteration Statements 128
Executing Code with the
while Statement 128
Working with the
do Statement 132
Counting and More with the
for Statement 134
The
foreach Statement 139
Revisiting
break and continue 139
Reviewing
goto 139
Exploring Labeled Statements 140
Nesting Flow 141
Summary 142
Q&A 142
Workshop 143
Quiz 143
Exercises 143
T
YPE & RUN 2 Guess the Number! 145
The Guess Type & Run 146
The WinGuess Type & Run 148
CHAPTER 5 The Core of C# Programming: Classes 153
Digging into Object-Oriented Programming 154
Returning Data from a Method 184
Naming Methods 185
Building the Method Body 185
Passing Values to Methods 190
Working with Static Methods 192
Access Attributes for Parameters 192
Types of Class Methods 198
Property Accessor Methods 198
Constructors 198
Destructors/Finalizers 204
Summary 206
Q&A 207
Workshop 207
Quiz 208
Exercises 208
C
HAPTER 7 Storing More Complex Stuff: Structures,
Enumerators, and Arrays 211
Working with Structures 212
Understanding the Difference Between Structures and Classes 212
Structure Members 213
Nesting Structures 215
Structure Methods 216
Structure Constructors 218
Structure Destructors 220
Clarifying with Enumerators 220
Changing the Default Value of Enumerators 223
Changing the Underlying Type of an Enumerator 225
Contents ix
Using Arrays to Store Data 228
Overloading Constructors 268
Understanding Method Signatures 271
Using a Variable Number of Parameters 272
Using
params with Multiple Data Types 275
Taking a More Detailed Look at
params 277
Working with the
Main Method and Command-Line Arguments 277
Understanding Scope 279
Working with Local Scope 279
Differentiating Class Variables from Local Variables 282
Modifying Class Scope with Modifiers 282
Creating Classes with No Objects 283
Using Private Constructors 284
x Sams Teach Yourself the C# Language in 21 Days
Revisiting Namespaces 286
Naming a Namespace 286
Declaring a Namespace 286
using and Namespaces 288
Summary 290
Q&A 291
Workshop 291
Quiz 292
Exercises 292
C
HAPTER 9 Handling Problems in Your Programs: Exceptions and Errors 295
Understanding the Concept of Handling Problems 296
Preventing Errors via Logical Code 296
What Causes Exceptions? 297
A Brief Look at Regions 333
Using Debuggers 333
Summary 333
Q&A 334
Contents xi
Workshop 335
Quiz 335
Exercises 336
T
YPE & RUN 3 Lines and Circles and Squares, “Oh My!” 339
C
HAPTER 10 Reusing Existing Code with Inheritance 349
Understanding the Basics of Inheritance 350
Delving into Simple Inheritance 351
Inheritance in Action 354
Using Base Methods in Inherited Methods 359
Exploring Polymorphism and Inherited Classes 359
Working with Virtual Methods 362
Working with Abstract Classes 365
Sealing Classes 368
The Ultimate Base Class:
Object 370
A Look at the
Object Class Methods 370
Boxing and Unboxing 371
Using the
is and as Keywords with Classes—Class Conversions 373
Using the
is Keyword 373
Using the
Quiz 418
Exercises 418
C
HAPTER 12 Tapping into OOP: Interfaces 421
Interfaces: A First Look 422
Classes Versus Interfaces 422
Using Interfaces 423
Why Use Interfaces? 423
Defining Interfaces 424
Defining an Interface with Method Members 424
Specifying Properties in Interfaces 428
Using Multiple Interfaces 430
Using Explicit Interface Members 432
Deriving New Interfaces from Existing Ones 435
Hiding Interface Members 435
Summary 437
Q&A 437
Workshop 438
Quiz 438
Exercises 438
C
HAPTER 13 Making Your Programs React with Delegates, Events,
and Indexers 441
Using an Indexer 442
Exploring Delegates 445
Working with Events 450
Creating Events 451
Understanding an Event’s Delegate 451
Deriving from the
EventArgs Class 451
CHAPTER 15 Using Existing Routines from the .NET Base Classes 507
Classes in the .NET Framework 508
The Common Language Specification 508
Namespace Organization of Types 509
Using the ECMA Standards 509
Checking Out the Framework Classes 510
Working with a Timer 510
Getting Directory and System Environment Information 513
Working with Math Routines 516
Working with Files 519
Copying a File 520
Getting File Information 524
Working with Simple Data Files 526
Understanding Streams 526
Understanding the Order for Reading Files 526
Creating and Opening Files 527
Working with Other File Types 535
Summary 535
Q&A 536
Workshop 536
Quiz 537
Exercises 537
xiv Sams Teach Yourself the C# Language in 21 Days
CHAPTER 16 Creating Windows Forms 539
Working with Windows and Forms 540
Creating Windows Forms 540
Compiling Options 540
Analyzing Your First Windows Form Application 542
Understanding the Application.Run Method 543
Customizing a Form 545
Using Pre-existing Microsoft Windows Dialog Boxes 607
Popping Up Your Own Dialog Box 610
Summary 613
Q&A 614
Workshop 614
Quiz 614
Exercises 615
Contents xv
TYPE & RUN 4 Tic Tac Toe 617
The Tic Tac Toe Code 618
C
HAPTER 18 Working with Data and Databases 629
Understanding Key Database Concepts 630
Understanding the Terminology 630
Introducing ADO.NET 631
Connecting to and Working with a Database 632
Making the Connection to the Database 633
Executing a Command 635
Retrieving Data with a DataReader 635
Closing the Database 637
Pulling It All Together 637
Adding, Updating, and Deleting Data 641
Other Database Concepts 644
Summary 645
Q&A 645
Workshop 645
Quiz 646
Exercises 646
C
HAPTER 19 Creating Remote Procedures: Web Services 647
HAPTER 21 A Day for Reflection and Attributes 691
Reflecting on Reflection 692
Understanding Attributes 697
What Are Attributes? 698
Using Attributes 698
Using Multiple Attributes 700
Using Attributes That Have Parameters 700
Defining Your Own Attribute 701
Accessing the Associated Attribute Information 706
Pulling It All Together 708
Single-Use Versus Multiuse Attributes 711
Reflecting on the Future of C# 712
Generics 712
What Are Iterators? 714
What Are Partial Types? 714
What Are Anonymous Methods? 715
Summary 715
Congratulations! 716
Q&A 716
Workshop 717
Quiz 717
Exercises 717
WEEK 3 Week In Review 719
Apply What You Know 719
Show What You Know 719
Appendices 721
APPENDIX A C# Keywords 723
abstract 723
as 723
base 723
if 727
implicit 727
in 728
int 728
interface 728
internal 728
is 728
lock 728
long 728
namespace 729
new 729
null 729
object 729
operator 729
out 729
override 729
params 729
partial 730
private 730
protected 730
public 730
readonly 730
ref 730
return 730
sbyte 731
sealed 731
set 731
short 731
sizeof 731
stackalloc 731
/recurse:<wildcard> 736
/reference:<file list> or /r:<file list> 736
/addmodule:<file list> 736
Resource 736
/win32res:<file> 736
/win32icon:<file> 736
/resource:<resinfo> or /res:<resinfo> 737
/linkresource:<resinfo> or /linkres:<resinfo> 737
Code Generation 737
/debug[+|-] 737
/debug:{full|pdbonly} 737
/optimize[+|-] or /o[+|-] 737
/incremental[+|-] or /incr[+|-] 737
Errors and Warnings 737
/warnaserror[+|-] 737
/warn:<n> or /w<n> 737
/nowarn:<warning list> 737
Programming Language 738
/checked[+|-] 738
/unsafe[+|-] 738
Miscellaneous 738
@<file> 738
/help or /? 738
/nologo 738
/noconfig 738
Advanced 738
/baseaddress:<address> 738
/bugreport:<file> 738
/codepage:<n> 738
/utf8output 739
Acknowledgments
As I stated earlier, although I create the structure and write the words, I don’t create a
book like this on my own. Many people’s contributions helped to make this a much bet-
ter book.
First, however, let me thank my wife and family for being patient and understanding
while I set the normal flow of life aside in order to focus on writing this book.
I’d also like to give my personal thanks to Mattias Sjogren and Anand Narayanaswamy.
Mattias proved to be one of the best technical editors that I have had review one of my
books. His suggestions and corrections to the first edition of this book truly brought it to
a higher level of quality. Anand, a Microsoft MVP, stepped in to review the second edi-
tion. Although his suggestions caused more work for me, I believe the end result is an
even better book for you, the reader.
In addition to the offical technical editor, this book has been read by thousands of others.
I want to thank the readers who took the time to suggest changes, improvements, or clar-
ifications. I take this feedback seriously and work a lot of it into reprints and errata.
I’d also like to thank the editors at Sams Publishing for their effort in building this book.
This includes Candy Hall, Mark Renfrow, Krista Hansing, Matt Purcell, Brad Shannon,
Nancy Albright, and others also spent large amounts of time focused on making this the
best book possible. They deserve to be acknowledged as well.
On a different note, this book would have been impossible to do without the support of a
number of people at Microsoft. Over the last several years, I have gained help from too
many people to list all of them. A number of people on the C# team—such as Nick
Hodapp, Tony Goodhew, and Eric Gunnerson—helped provide information on C# in
addition to answering many of my questions.
¨
Because this book provides the chance to publicly acknowledge people, I’d also like to
thank a number of other people at Microsoft for their help over the last several years—
either on this book or on many other projects. This includes Eric Ewing, Stacey Giard,
Brad Goldberg, Tony Goodhew, Rob Howard, Jeff Ressler, Scott Guthrie, Connie
Sullivan, Dee Dee Walsh, Dennis Bye, Bob Gaines, Robert Green, David Lazar, Greg