Learning C# is a primer on the C# language, in the context of the .NET development environment, and also on object-oriented programming.This book focuses on the fundamentals of the C# pr
Trang 1help you build a solid foundation in NET and show how to apply your skills by using dozens of tested examples You will learn how to develop various kinds of applications including those that work with databases and web services Whether you have a little object-oriented programming experience or you are new to programming
altogether, Learning C# will set you firmly on your way.
Trang 3Section 3.3 Defining a Class
Section 3.4 Class Relationships
Section 3.5 The Three Pillars of Object-Oriented Programming Section 3.6 Encapsulation
Trang 4Chapter 9 Inside Methods
Section 9.1 Overloading Methods
Section 9.2 Encapsulating Data with Properties Section 9.3 Returning Multiple Values
Section 14.4 Extending Interfaces
Section 14.5 Combining Interfaces
Section 14.6 Overriding Interface Implementations Section 14.7 Explicit Interface Implementation
Trang 5Section 16.2 Array Lists
Section 16.3 Queues
Section 16.4 Stacks
Section 16.5 Copying from a Collection Type to an Array
Section 18.8 Exception Class Methods and Properties Section 18.9 Custom Exceptions
Trang 6O P R S T U V W
Colophon Index
Trang 7Printed in the United States of America
Published by O'Reilly & Associates, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly & Associates books may be purchased for educational,
business, or sales promotional use Online editions are also available formost titles (http://safari.oreilly.com) For more information contact ourcorporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com
Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logoare registered trademarks of O'Reilly & Associates, Inc Many of the
designations used by manufacturers and sellers to distinguish their
products are claimed as trademarks Where those designations appear inthis book, and O'Reilly & Associates, Inc was aware of a trademark
claim, the designations have been printed in caps or initial caps Theassociation between the image of a goldfish and the topic of Learning C#
is a trademark of O'Reilly & Associates, Inc
While every precaution has been taken in the preparation of this book,the publisher and the author assume no responsibility for errors or
omissions, or for damages resulting from the use of the information
contained herein
Trang 8In July 2000, Microsoft announced the release of its new NET platform,which represented a major change in the way people think about
programming .NET facilitates object-oriented Internet development C#
is a programming language that was developed specifically for the
purpose of writing applications for the NET platform C# builds on
lessons learned from other languages, like C (high performance), Java(high security), and Visual Basic (rapid development) And this newlanguage is ideally suited for developing distributed web applications
Trang 9Learning C# is a primer on the C# language, in the context of the NET
development environment, and also on object-oriented programming.This book focuses on the fundamentals of the C# programming
language, both syntactical and semantic After mastering these concepts,you should be ready to move on to a more advanced programming guidethat will help you create large-scale web and Windows applications
Afterword, provides a number of suggestions for your continued study ofC# and NET development
Trang 10Learning C# was written for programmers with little or no object-oriented
programming experience, as well as for novice programmers Thosecoming from another language may have a slight advantage, but I'vetried to provide an on-ramp for beginners as well, by defining all terms,demonstrating the relationships among the various constructs, and
reviewing key concepts along the way
Trang 11Chapter 5, introduces the basic syntax and structure of the C# language,including the intrinsic types, variables, statements, and expressions
Chapter 9, delves into the specific programming instructions you'll write
to define the behavior of objects
Chapter 10, introduces the debugger integrated into the Visual Studio
Trang 12Chapter 11, explores two of the key concepts behind object-oriented
programming and demonstrates how you might implement them in yourcode
Chapter 12, explains how to add standard operators to the types youdefine
Chapter 13, introduces the structure or struct, a programmer-defined typesimilar to a class, but with specific and more limited functionality
Chapter 14, explains how you can define a set of behaviors (an interface)that any number of classes might implement
Chapter 15, introduces the array, an indexed collection of objects that areall the same type Arrays are one of the collection types recognized byC#
Chapter 16, describes some of the other C# collections, including stacksand queues
Chapter 17, discusses the manipulation of strings of characters, the C#string class, and regular expression syntax
Chapter 18, explains how to handle errors and abnormal conditions thatmay arise in relation to your programs
Chapter 19, discusses how to write code to respond to programmingoccurrences like mouse clicks, keystrokes, and other events; event
handling is often accomplished by the use of delegates, which are
objects that encapsulate any method that matches the delegate's
specification
Afterword, describes where you might go to learn more about C# and.NET programming, including other books, web sites, newsgroups, and
so forth
The book concludes with an appendix of C# Keywords.
Trang 13The following font conventions are used in this book:
Italic
Used for pathnames, filenames, program names, Internet addresses,such as domain names and URLs, and new terms where they aredefined
Constant Width
Used for command lines and options that should be typed verbatim,C# keywords, and code examples
Constant Width Italic
Used for replaceable items, such as variables or optional elements,within syntax lines or code
Constant Width Bold
Used for emphasis within program code
Pay special attention to notes set apart from the text with the followingicons:
This is a tip It contains useful supplementary information about the topic at hand.
This is a warning It helps you solve and avoid annoying problems.
Trang 14As part of my responsibilities as author, I provide ongoing support for mybooks through my web site :
http://www.LibertyAssociates.com
On this web site, you'll also find the source code for all the examples in
Learning C#, as well as access to a book-support discussion group with a
section set aside for questions about C# Before you post a question,however, please check the FAQ (Frequently Asked Questions) list andthe errata file on my web site If you check these files and still have aquestion, then please go ahead and post to the discussion center
The most effective way to get help is to ask a very precise question oreven to create a very small program that illustrates your area of concern
or confusion You may also want to check the various newsgroups anddiscussion centers on the Internet Microsoft offers a wide array of
newsgroups, and Developmentor (http://www.develop.com) has
wonderful NET email discussion list, as does Charles Carroll at
http://www.asplists.com
Trang 15We have tested and verified the information in this book to the best of ourability, but you may find that features have changed (or even that wehave made mistakes!) Please let us know about any errors you find, aswell as your suggestions for future editions, by writing to:
http://www.oreilly.com
and the O'Reilly NET DevCenter:
http://www.oreillynet.com/dotnet
Trang 16interoperable, and emerging Microsoft NET programming and Webservices technologies
Trang 17To ensure that Learning C# is accurate, complete, and targeted at the
needs and interests of programmers, I enlisted the help of some of thebrightest people I know, including Dan Hurwitz, Seth Weiss, and SueLynch
John Osborn signed me to O'Reilly, for which I will forever be in his debt.Claire Cloutier and Tatiana Diaz helped make this book better than whatI'd written Rob Romano created a number of the illustrations and
improved the others Tim O'Reilly provided support and resources, andI'm grateful A special thank you to Val Quercia, who added great value tothis book, as she has to many others If this book is clear and
understandable, it is due to her vigilance
Trang 18Learning C# introduces C# specifically, and the NET development
platform more generally, to programmers with little or no object-orientedprogramming experience Along the way, you will learn a great deal aboutwriting high-quality, industrial-strength programs for NET
This brief introduction will show you how C# fits into the NET picture,what you can do with the language, and what benefits this language hasover its predecessors
You will also learn some of the concepts integral to object-oriented
programming, which has revolutionized how web and Windows
applications are developed Object-oriented programming is closely tied
to the semantics of the C# language, that is, the meaning behind thecode you write Obviously, you need to have a basic understanding of thesyntax of the C# language, but you also need to understand what you areactually trying to accomplish
Trang 19In the past, you might have learned a language like C or Java withoutmuch concern about the platform on which you would be programming.These cross-platform languages were as comfortable on a Unix box asthey were on a PC running Windows
C#, however, was created specifically for NET While NET may becomecross-platform some day soon a Unix port is reportedly in the offing fornow the overwhelming majority of NET programs will be written to run on
a machine running NET At the time of this writing, that means a
Windows machine
Trang 20When Microsoft announced C# in July 2000, its unveiling was part of amuch larger event: the announcement of the NET platform The NETplatform is a development framework that provides a new way to createWindows applications However, NET goes beyond traditional Windowsprogramming to facilitate creating web applications quickly and easily
Microsoft says it is devoting 80% of its research and development budget
to NET and its associated technologies The results of this commitmentare impressive For one thing, the scope of NET is huge The platformconsists of three separate product groups:
A set of languages, including C# and Visual Basic NET; a set ofdevelopment tools, including Visual Studio NET; and powerful tools
for building applications, including the Common Language Runtime
(CLR), a platform for compiling, debugging, and executing NETapplications
Console applications, which display no graphics
Windows applications, which use the standard Windows interfaceWeb applications, which can be accessed with a browser
Trang 21This book will focus primarily on the basics of the C# language, mostlyusing simple console applications to illustrate language fundamentals.
Trang 22and the Framework Class Library (FCL), which provides an enormous
number of predefined types or classes for you to use in your programs.You will learn how to define your own classes in Chapter 8 Completecoverage of all the FCL classes is beyond the scope of this book For
more information, see C# in a Nutshell (O'Reilly & Associates).
Trang 23The C# language is disarmingly simple, but C# is highly expressive when
it comes to implementing modern programming concepts C# includes allthe support for structured, component-based, object-oriented
programming that one expects of a modern language built on the
shoulders of C++ and Java
A small team led by two distinguished Microsoft engineers, Anders
Hejlsberg and Scott Wiltamuth, developed the C# language Hejlsberg isalso known for creating Turbo Pascal, a popular language for PC
programming, and for leading the team that designed Borland Delphi,one of the first successful Integrated Development Environments forclient/server programming
centric, high-performance language for NET development C# is simple
The goal of C# is to provide a simple, safe, object-oriented, Internet-because there are relatively few keywords This makes it easy to learn
and easy to adapt to your specific needs
Keywords are special words reserved by the language that have a specific meaning within all C# programs Keywords include if, while, and for You'll learn about these keywords
in the coming chapters.
C# is considered safe because it provides support in the language to findbugs early in the development process This makes for code that is
easier to maintain and programs that are more reliable
C# was designed, from the very start, to support object-oriented
programming This book will explain not only how to write object-orientedprograms, but also why object-oriented programming has become sopopular The short answer is this: programs are becoming increasinglycomplex, and object-oriented programming techniques help you manage
Trang 24C# was designed for NET, and NET was designed for developing weband web-aware programs The Internet is a primary resource in most.NET applications
Finally, C# was designed for professional high-performance
programming
Trang 25At the most fundamental level, a C# application consists of source code.
Source code is human-readable text written in a text editor A text editor
is like a word processor, but it puts no special characters into the file tosupport formatting, only the text A classic text editor is Notepad
Trang 26Once you write your program in an editor, you must compile it For thatyou need a compiler You will learn how to use the C# compiler in
Chapter 2 Once compiled, your program must be run and tested
While you can perform all of these tasks using Notepad (or another text
editor) and various command-line tools, your programming life will bemuch easier if you use the Integrated Development Environment (IDE)called Visual Studio NET VS.NET was designed with NET development
in mind and greatly simplifies the writing of C# program code
Trang 27The Visual Studio NET Integrated Development Environment providesenormous advantages to the C# programmer This book tacitly assumesthat you'll use Visual Studio NET for your work However, the discussionfocuses more on the language and the platform than on the tools
Nonetheless, Chapter 4 provides a good introduction to the IDE in somedetail Chapter 10 returns to the IDE to examine the debugger, which willhelp you find and correct problems in your code
Trang 28composed of two Microsoft development technologies: Web Forms andWeb Services While the development of fully realized web applicationsusing these technologies is beyond the scope of this book, learning thebasics of the C# language will certainly get you started in the right
direction C# is generally acknowledged to be the language of choice forASP.NET development
Typically, you'll create an ASP.NET application when you want yourprogram to be available to end users on any platform (e.g., Windows,Mac, Unix) By serving your application over the Web, end users canaccess your program with any browser
When you want the richness and power of a native application runningdirectly on the Windows platform, alternatively you might create a
desktop-bound Windows application The NET tools for building
Windows applications are called Windows Forms; a detailed analysis ofthis technology is also beyond the scope of this book
However, if you don't need a Graphical User Interface (GUI) and justwant to write a simple application that talks to a console window (i.e.,
Trang 29Web, Windows, and console applications are described and illustrated inthe following pages
Console applications
A console application runs in a console window, as shown in Figure2-1 A console window (or DOS box) provides simple text-basedoutput
Figure 2-1 A console application
Console applications are very helpful when learning a language becausethey strip away the distraction of the Graphical User Interface Ratherthan spending your time creating complex windowing applications, youcan focus on the details of the language constructs, such as how youcreate classes and methods, how you branch based on runtime
conditions, and how you loop All these topics will be covered in detail incoming chapters
Windows applications
A Windows application runs on a PC's desktop You are alreadyfamiliar with Windows applications such as Microsoft Word or Excel.Windows applications are much more complex than console
applications and can take advantage of the full suite of menus,
controls, and other widgets you've come to expect in a modern
desktop application Figure 2-2 shows the output of a simple
windows application
Trang 30ASP.NET applications
An ASP.NET application runs on a web server and delivers its
functionality through a browser, typically over the Web ASP.NETtechnology facilitates developing web applications quickly and easily.Figure 2-3 shows a message from a simple ASP.NET application
Figure 2-3 An ASP.NET application
Although most commercial applications will be either Windows orASP.NET programs, console applications have a tremendous
advantage in a C# primer Windows and ASP.NET applications bring
a lot more overhead; there is great complexity in managing the
window and all the events associated with the window (Events are
Trang 31This book does not go into all the myriad details of building robust Windows and ASP.NET applications For complete
coverage of these topics, please see Programming ASP.NET and Programming NET Windows Applications, both by Jesse
Liberty and Dan Hurwitz (O'Reilly).
Trang 32A program consists of English-language instructions called source code.The syntax for these instructions is strictly defined by the language
Source code consists of a series of statements A statement is an
instruction to the complier Each instruction must be formed correctly, andone task you'll face when learning C# will be to learn the correct syntax ofthe language For example, in C# every statement ends with a semi-colon
Each instruction has a semantic meaning that expresses what you aretrying to accomplish Although you must follow the syntax, the semantics
oriented programs This book will provide insight into both the syntax andthe semantics of good C# programs
of the language are far more important in developing effective object-Save the source code you write in a text file You can write this sourcecode file using any simple text editor (such as Notepad), or you can usethe Visual Studio NET Integrated Development Environment (IDE)
Visual Studio NET is described in Chapter 4
Once you write your program, you compile it using the C# compiler Theend result of compiling the program is an application
Trang 33In this chapter, you will create a very simple application that does nothingmore than display the words "Hello World" to your monitor This consoleapplication is the traditional first program for learning any new language;
it demonstrates some of the basic elements of a C# program
Once you write your "Hello World" program and compile it, this chapterwill provide a line-by-line analysis of the source code This analysis givessomething of a preview of the language; Chapter 5 describes the
fundamentals much more fully
As explained earlier, you can create C# programs with any text editor.You can, for example, create each of the three programs shown
previously (in Figures 2-1, 2-2, and 2-3) with Notepad To demonstratethat this is possible, you'll write your very first C# program using Notepad
Begin by opening Notepad and typing in the program exactly as shown inExample 2-1
Trang 34Microsoft provides a command window with the correct environment
variables set Open the command window by selecting the following
menu items in this order:
Trang 36The single greatest challenge when learning to program is that you mustlearn everything before you can learn anything Even this simple "HelloWorld" program uses many features of the language that will be
discussed in coming chapters, including classes, namespaces,
statements, static methods, objects, strings, inheritance, blocks, libraries,and even something called polymorphism!
It is as if you were learning to drive a car You must learn to steer,
accelerate, brake, and understand the flow of traffic Right now we'regoing to get you out on the highway and just let you steer for a while.Over time you'll learn how to speed up and slow down Along the wayyou'll learn to set the radio and adjust the heat so that you'll be morecomfortable In no time you'll be driving, and then won't your parentsbegin to worry
2.3.1 Line-by-Line Analysis
Hang on tight, we're going to zip through this quickly and come back tothe details in subsequent chapters
The first line in the program defines a namespace:
namespace NotePad
You will create many names when programming in C# Every object andevery type of object must be named It is possible for the names youassign to conflict with the names assigned by Microsoft or other vendors
A namespace is a way to say "these names are mine."
In this program, you've created a namespace called NotePad Each
namespace must be enclosed in braces ({}) Thus, the second line ofthe Hello World program is an open brace to mark the beginning of theNotePad namespace The open brace is matched by a closing brace at
Trang 37Within the braces of the namespace, you write other programming
constructs For instance, you might define what is called an object Everyobject named within these braces is implicitly prefixed with the nameNotePad The dot operator (.) separates the namespace from the name
of the object within the namespace Thus, if you were to create an objectMyObject within the namespace NotePad, the real name of that objectwould be NotePad.MyObject You can read this as either "NotePad dotMyObject" or "NotePad MyObject" Actually, you use the dot operatorquite a lot; you'll see various other uses as we proceed
Classes define a category, or type, of object In C# there are thousands
of classes A class is a new, user-defined type Classes are used to
define Windows controls (buttons, list boxes, etc.), as well as types ofthings (employees, students, telephones, etc.) in the program you arewriting Some classes you create yourself, and some you obtain from the.NET Framework Each class must be named
Classes are the core of C# and object-oriented programming You'll learnabout classes in detail in Chapter 3, as well as in Chapter 5
The third line in our Hello World program creates a class named, aptly,HelloWorld Like a namespace, a class is defined within braces Thefollowing code represents the opening of the HelloWorld class definition:
class HelloWorld
{
A method is a small block of code that performs an action The Main()method is the "entry point" for every C# console application; it is whereyour program begins The next few lines in Hello World mark the
beginning of the Main() method:
static void Main()
{
Trang 38A comment (here in bold) appears just before the start of the Main()method:
// every console app starts with Main
static void Main()
{
A comment is just a note to yourself You insert comments to make thecode more readable to programmers You can place comments
anywhere in your program that you think the explanation will be helpful;they have no effect on the running program
C# recognizes three styles of comments The comment in Hello Worldbegins with two slashes (//) The slashes indicate that everything to theright on the same line is a comment
The second style is to begin your comment with a forward slash followed
by an asterisk (/*) and to end your comment with the opposite pattern(*/) These pairs of characters are called the opening C-style commentand the closing C-style comment, respectively
These comment symbols were inherited from the C language thus the names used to identify them They are also used in C++ and Java.
Everything between these comment symbols is a comment C-stylecomments can span more than one line, as in the following:
/* This begins a comment
This line is still within the comment
Trang 39Normally, methods can be called only if you have an object, but staticmethods are special and can be called without an object (The use ofstatic methods, other than Main(), is fairly advanced and won't be
a value, it is declared void The keyword void is a signal to the compilerthat your method will not return a value to the calling method
The operating system calls Main() (when the program is invoked) It ispossible for Main() to return a value (typically an error code) that might be
Trang 40return a value since you will not be calling this program from a batch file.Every method name is followed by parentheses
static void Main()
It is possible to pass values into a method so that the method can
manipulate or use those values These values are called parameters orarguments (Method parameters are covered in Chapter 9.) In this case,Main() has no parameters All methods are enclosed within braces
Within the braces for Main() is a single line of code:
System.Console.WriteLine("Hello world!");
The Console is an object that represents your screen The Console class
is defined within the System namespace, and so its full identification isSystem.Console
The Console class has a static method, WriteLine(), which you accessnot with an instance of Console, but through the Console class itself.Since you access the method with the dot operator, you write
System.Console.WriteLine
The WriteLine() method declares a single parameter: the string you want
to display When you pass a string in to the method, the string is an
argument The argument ("Hello world") corresponds to the parameterthe method expects, and the string is displayed The complete call to themethod is:
System.Console.WriteLine("Hello world!");
If you will use many objects from the System namespace, you can savetyping by telling the compiler that many of the objects you'll refer to are inthat namespace You do so by adding a using declaration to the
beginning of your program:
using System;
Once you add this line, you can use the Console class name without