Thinking
in
C#
Larry O’Brien
and
Bruce Eckel
Thinking
in
C#
Larry O’Brien
and
Bruce Eckel Prentice Hall
Upper Saddle River, New Jersey 07458
www.phptr.com
Dedication
For Tina, who makes me happy — LOB
Index 929
What’s Inside
Preface: Computer
Language 1
Prerequisites 2
Learning C# 3
Goals 4
Online documentation 5
Exercises 5
Source code 5
Coding standards 7
C# and .NET versions 8
Seminars and mentoring 8
Errors 8
Note on the cover design 8
Acknowledgments 9
1: Those Who Can, Code 1
Software economics 3
C# and the Internet 4
Static sites 5
Dynamic sites 5
Peer-to-peer 5
Web services 6
Security 7
Analysis, design, and Extreme
Programming 7
Multithreading 44
Persistence 45
Remote objects 46
Summary 46
3: Hello, Objects
You manipulate objects with
references 49
You must create all the objects50
Where storage lives 50
Arrays in C# 52
Special case: value types 52
You never need to destroy an
object 53
Scoping 53
Scope of objects 54
Creating new data types: class55
Fields, properties, and methods 55
Methods, arguments, and
return values 58
The argument list 59
Attributes and meta-behavior60 Delegates 61
Properties 62
Creating new value types 63
Enumerations 64
Logical operators 103
Short-circuiting 104
Bitwise operators 105
Shift operators 106
Ternary if-else operator 111
The comma operator 112
Common pitfalls when using
operators 113
Casting operators 113
Literals 114
Promotion 116
C# has sizeof 116
C#’s preprocessor 116
Precedence revisited 118
A compendium of operators 118
Execution control 130
true and false 130
if-else 130
return 131
Iteration 132
do-while 133
for 133
foreach 135
The comma operator 136
break and continue 136
The infamous goto 138
switch 144
Summary 146
Exercises 146
Array initialization 185
The params method modifier 189
Multidimensional arrays 190
What a difference a rectangle makes194
Summary 195
Exercises 196
6: Hiding the
Implementation 199
Organizing with namespaces200
Creating unique names 202
Using #define to change behavior204
C#’s access specifiers 206
public: interface access 206
internal 207
private: you can’t touch that! 208
protected 210
Interface and implementation211
Class access 213
Summary 215
Exercises 217
7: Reusing Classes 219
Composition syntax 220
Inheritance syntax 223
Initializing the base class 225
Combining composition and
inheritance 229
Guaranteeing proper cleanup 230
Choosing composition vs.
inheritance 234
Explicit and implicit type
conversions 283
Operator overloading design
guidelines 285
Abstract classes and methods285
Constructors and
polymorphism 289
Order of constructor calls 290
Behavior of polymorphic methods
inside constructors 292
Designing with inheritance .294
Pure inheritance vs. extension 295
Downcasting and run-time type
identification 298
Interfaces 302
“Multiple inheritance” in C# 305 Extending an interface with
inheritance 309
Summary 310
Exercises 311
9: Coupling and Cohesion 315
Arrays 349
Arrays are first-class objects 351
The Array class 355
Array’s static methods 355
Array element comparisons 358
What? No bubbles? 360
Unsafe arrays 362
Get things right… 366
… then get them fast 368
Array summary 375
Introduction to data structures380
Queues and stacks 381
ArrayList 384
BitArray 386
Dictionaries 387
Hashtable 388
ListDictionary 391
SortedList 391
String specialists 392
One key, multiple values 392
Customizing hashcode providers394
String specialists:
StringCollection and
StringDictionary 396
Container disadvantage:
unknown type 397
Using CollectionBase to make
type-conscious collections 399
Supertype matching 444
Exceptions have a helplink 444
Creating your own exceptions445
C#’s lack of checked exceptions451
Catching any exception 452
Rethrowing an exception 453
Elevating the abstraction level 453
Standard C# exceptions 455
Performing cleanup with
finally 456
What’s finally for? 457
Finally and using 461
Pitfall: the lost exception 462
Constructors 464
Exception matching 468
Exception guidelines 469
Summary 470
Exercises 470
12: I/O in C# 473
File, Directory, and Path 473
A directory lister 473
Checking for and creating
directories 474
Isolated stores 476
Input and output 478
Types of Stream 479
Text and binary 479
Working with different sources .480
The Global Assembly Cache 532
Designing with attributes 537
Beyond objects with aspects 543
Summary 543
Exercises 545
14: Programming Windows
Forms
Delegates 548
Designing With Delegates 550
Multicast delegates 552
Events 555
Recursive traps 558
The genesis of Windows Forms561
Creating a Form 562
GUI architectures 563
Using the Visual Designer 563
Form-Event-Control 570
Presentation-Abstraction-
Control 573
Model-View-Controller 577
Layout 582
Non-code resources 585
Creating satellite assemblies 590 Constant resources 591
What about the XP look? 593
Fancy buttons 596
Tooltips 599
Your canvas: the Graphics
Class 659
Understanding repaints 661
Control: paint thyself 662
Scaling and transforms 665
Filling regions 672
Non-rectangular windows 677
Matrix transforms 678
Hit detection 686
Fonts and text 688
Printing 690
Bitmaps 692
Rich clients with interop 698
COM Interop and the
WebBrowser control 698
COM Interop challenges 701
Non-COM Interop 702
Summary 707
Exercises 708
16: Multithreaded
Programming
Responsive user interfaces 711
.NET’s threading model 714
Running a thread 716
Waiting for a thread to complete 717
Multiple threads in action 719
Threading for a responsive interface721
Interrupting a sleeping Thread 724
XML serialization 783
Deserializing XML 789
Can’t serialize cycles 789
Schemas 796
ADO and XML 798
XPath navigation 801
An XPath explorer 807
Transforming a document 815
Summary 821
Exercises 822
18: Web Programming 824
Identifying a machine 824
Sockets 826
Whois for ZoneAlarm 826
Receiving incoming connections833
Serving multiple clients 837
Communicating with Microsoft
Messenger 841
Creating and receiving HTTP
requests 852
Asynchronous Web requests 858
From Web programming to
Web Services 864
Insanely simple Web services 865
Maintaining state 868
Web services vs. Web APIs 868
Consuming Web services 872
thinking. Languages channel us down particular avenues
of thought, make certain ideas as obvious as a grand
concourse and others as confusing and mysterious as a
back alley. Different computer languages facilitate
different things; there are computer languages that
facilitate graphics programming and others that are best
for text manipulation, many that excel in data
relationships, and several whose raison d’être is pure
performance. C# is a language for professional
programming. The ideas that it facilitates, the capabilities
that it makes easy, are those that lead to the rapid
development of robust, scalable programs that deliver
client value and are easily modifiable.
You can’t look at C# as just a list of keywords that must be memorized to get a
clean compile or as a conveyor belt for calling library functions. You must look at
it as an interlocking set of features that support the efficient creation of object-
oriented, high-quality programs. And to understand C# in this way, you must
understand both its strengths and its weaknesses, and how they relate to the best
practices that are known for developing software and the challenges that remain.
This book discusses programming as a profession, not as an academic discipline,
and the pragmatic use of C# and the .NET Framework SDK. Thus, the chapters
present their features based on what we the authors believe to be the core issues
of the subject and the way in which C# addresses those issues.
A chapter in Thinking in C# should take you to the point where you can take
charge of your own further education by whatever means you find most
constructive. For some topics, you may find the background provided by the book
sufficient and concern yourself only with fleshing out the details of the .NET
ii Thinking in C# www.ThinkingIn.NET
library classes and methods in the area. Hopefully, some topics will excite your
means that you will be required to expend a little more effort.
This book does not assume that you’re familiar with object-oriented
programming (OOP) and the first half of the book can be seen as an extended
tutorial on object-oriented programming at least as much as a tutorial on C# per
se. No formal background in computer science is expected. 1
Larry has been paid to write technical white papers for Microsoft.
Preface: Computer Language iii
Although references will often be made to language features in other languages
such as C++ and Java, these are not intended to be insider comments, but instead
to help all programmers put C# in perspective with those languages. All good
programmers are polyglots and the greatest value proposition of the .NET
Framework is that it supports multiple languages.
Learning C#
Picasso is reputed to have said “Computers are worthless; they can only give you
answers.” The same could be said of books. No book can teach you C#
programming, because programming is a creative process. The only way to learn
any language is to use it in a variety of situations, to gradually internalize it as you
solve increasingly difficult problems with it. To learn C#, you must start
programming in C#.
This is not to say that the best way to learn C# is on the job. For one thing,
companies don’t typically allow programmers to work in a language in which they
have no experience. More significantly, your job is to deliver value to your
customers, not to learn the nuances of C# and the .NET Framework.
For many people, seminars are the best environment for rapid learning. There
are many reasons for this: the interactions with the teachers and fellow students,
the explicit dedication of several days to achieving specific educational goals, or
bite-sized pieces that can be taught in a reasonable amount of time, followed by
exercises that are feasible to accomplish in a classroom situation.
The goals of this book are to:
1. Present the material one simple step at a time so that you can easily
digest each concept before moving on.
2. Use examples that are as simple and short as possible. This generally
prevents “real world” problems, but it’s better to understand every detail
of an example rather than being impressed by the scope of the problem it
solves.
3. Carefully sequence the presentation of features so that you aren’t seeing
something that you haven’t been exposed to. Of course, this isn’t always
possible; in those situations, a brief introductory description is given.
4. Give a pragmatic understanding of the topic, rather than a
comprehensive reference. There is an information importance hierarchy,
and there are some facts that 95 percent of programmers will never need
to know and that just confuse people and add to their perception of the
complexity of the language. To take an example from C#, if you
memorize the operator precedence table on page 118, you can write
clever code. But if you need to think about it, it will also confuse the
reader/maintainer of that code. So forget about precedence, and use
parentheses when things aren’t clear.
5. Keep each section focused enough so that the range of topics covered is
digestible. Not only does this keep the audience’s minds more active and
Preface: Computer Language v
involved during a hands-on seminar, but it gives the reader a chance to
tackle the book within the busy time constraints that we all struggle with.
6. Provide you with a solid foundation so that you can understand the
issues well enough to move on to more difficult coursework and books.
Online documentation
Professional educators should contact the authors for a curriculum including pre- and
post test evaluation criteria and sample solutions.
vi Thinking in C# www.ThinkingIn.NET
mirrored version is actually the most recent edition. You may distribute the code
in classroom and other educational situations.
The primary goal of the copyright is to ensure that the source of the code is
properly cited, and to prevent you from republishing the code in print media
without permission. (As long as the source is cited, using examples from the book
in most media is generally not a problem.)
In each source code file you will find a reference to the following copyright notice:
//:! :Copyright.txt
Copyright ©2002 Larry O'Brien
Source code file from the 1st edition of the book
"Thinking in C#." All rights reserved EXCEPT as
allowed by the following statements:
You can freely use this file
for your own work (personal or commercial),
including modifications and distribution in
executable form only. Permission is granted to use
this file in classroom situations, including its
use in presentation materials, as long as the book
"Thinking in C#" is cited as the source.
Except in classroom situations, you cannot copy
and distribute this code; instead, the sole
distribution point is
(and official mirror sites) where it is
freely available. You cannot remove this
copyright and notice. You cannot distribute
modified versions of the source code in this
You may use the code in your projects and in the classroom (including your
presentation materials) as long as the copyright notice that appears in each
source file is retained.
Coding standards
In the text of this book, identifiers (function, variable, and class names) are set in
bold. Most keywords are also set in bold, except for those keywords that are used
so much that the bolding can become tedious, such as “class.” Important
technical terms (such as coupling) are set in italics the first time they are used.
The coding style used in this book is highly constrained by the medium. Pixels are
cheap; paper isn’t. The subject of source-code formatting is good for hours of hot
debate, so suffice it to say that the formatting used in this book is specific to the
goals of the book. Since C# is a free-form programming language, you and your
teammates can use whatever style you decide is best for you.
The programs in this book are files that are included by the word processor in the
text, directly from compiled files. Thus, the code files printed in the book should
all work without compiler errors. The errors that should cause compile-time error
messages are commented out with the comment //! so they can be easily
discovered and tested using automatic means. Errors discovered and reported to
the author will appear first in the distributed source code and later in updates of
the book (which will also appear on the Web site www.ThinkingIn.Net).
viii Thinking in C# www.MindView.net
C# and .NET versions
All of the code in this book compiles and runs with Microsoft’s .NET Framework
1.1.4322and Microsoft’s Visual C# .NET Compiler 7.10.2215.1, which were
released in the Fall of 2002.
Seminars and mentoring
Bruce Eckel’s company MindView provides a wide variety of learning
experiences, ranging from multiday in-house and public seminars to get-
missing their opportunity to actively participate in the opening of a great
intellectual frontier.
Acknowledgments
(by Larry O’Brien)
First, I have to thank Bruce Eckel for entrusting me to work with the Thinking
In… structure. Without this proven framework, it would have been folly to
attempt a work of this scope on a brand-new programming language.
I’m going to exercise my first-time book author’s perquisite to reach back in time
to thank J.D. Hildebrand, Regina Ridley, and Don Pazour for hiring a blatantly
unqualified hacker with a penchant for Ultimate Frisbee and giving me the
greatest programming job in the world – Product Review Editor of Computer
Language magazine. For half a decade I had the ridiculous privilege of being able
to ask many of the brightest and most interesting people in the software
development industry to explain things in terms that I could understand. It
would be folly to try to begin to list the writers, readers, editors, speakers, and
students to whom I am indebted, but I have to thank P.J. Plauger and Michael
Abrash for demonstrating a level of readability and technical quality that is
inspiring to this day and Stan Kelly-Bootle for his trail-blazing work in
developing a programmer’s lifestyle worthy of emulation (e.g., at your 70
th
birthday party there should be an equal mix of language designers, patrons of the
symphony, and soccer hooligans).
Alan Zeichick urged me to write a book on C#, a display of considerable faith
considering the number of times I have missed deadlines on 1,000-word articles
for him. Claudette Moore and Debbie McKenna of Moore Literary Agency were
tremendously helpful in representing me and Paul Petralia of Prentice Hall
always agreed that the quality of the book took precedence over schedule
pressure. Mark Welsh’s commitment to the book even after his internship ended
is something for future employers to note.