Here's what's new: A detailed explanation of C# 2.0 An introduction to Visual Studio 2005, a tool set for building Windows and web applications More than 200 questions and programming ex
Trang 1By Jesse Liberty, Brian MacDonald
Publisher: O'Reilly Pub Date: February 2006 Print ISBN-10: 0-596-10209-7 Print ISBN-13: 978-0-59-610209-8 Pages: 552
Table of Contents | Index
If you're a novice programmer and you want to learn C#, there aren't many books that will guide you Most C# books are written for experienced C++ and Java programmers.
That's why Jesse Liberty, author of the best-selling books Programming C# and
Programming ASP.NET, has written an entry-level guide to C#
Written in a warm and friendly manner, Learning C# assumes no prior programming
experience, and provides a thorough introduction to Microsoft's premier NET language The book helps you build a solid foundation in NET, and shows you how to apply your skills through the use of dozens of tested examples You'll learn about the syntax and structure of the C# language, including operators, classes and interfaces, structs, arrays, and strings.
Better yet, this updated edition of Learning C# has been completely revised to include the
very latest content and teaching techniques Here's what's new:
A detailed explanation of C# 2.0
An introduction to Visual Studio 2005, a tool set for building Windows and web applications
More than 200 questions and programming exercises to help you better judge your understanding of the material
A greater emphasis on event handling
Information on generics and generic collections
Trang 3By Jesse Liberty, Brian MacDonald
Publisher: O'Reilly Pub Date: February 2006 Print ISBN-10: 0-596-10209-7 Print ISBN-13: 978-0-59-610209-8 Pages: 552
Trang 6Section 13.4 The is and as Operators
Section 13.5 Extending Interfaces
Section 13.6 Combining Interfaces
Section 13.7 Overriding Interface Implementations Section 13.8 Explicit Interface Implementation Section 13.9 Summary
Section 13.10 Quiz
Trang 7Section 16.5 The try and catch Statements
Section 16.6 How the Call Stack Works
Section 16.7 Creating Dedicated catch Statements Section 16.8 The finally Statement
Section 16.9 Exception Class Methods and Properties Section 16.10 Custom Exceptions
Trang 8Section A.13 Chapter 13: Interfaces
Section A.14 Chapter 14: Generics and Collections
Section A.15 Chapter 15: Strings
Section A.16 Chapter 16: Throwing and Catching Exceptions Section A.17 Chapter 17: Delegates and Events
Section A.18 Chapter 18: Creating Windows Applications Section A.19 Chapter 19: Programming ASP.NET Applications About the Author
Trang 9Colophon Index
Trang 10by Jesse Liberty and Brian MacDonald
Copyright © 2006, 2002 O'Reilly Media, Inc All rights reserved.Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 or
Trang 11ISBN: 0-596-10209-7
[M]
Trang 13
programmer productivity
Trang 14Learning C# 2005, Second Edition is a primer on the C# 2005
language specifically, and object-oriented software development
in general This book focuses on the fundamentals of the C#programming language, both syntactical and semantic Aftermastering these concepts, you should be ready to move on to amore advanced programming guide that will help you createlarge-scale web and Windows applications
Trang 15Learning C# 2005 was written for programmers with little or no
object-oriented programming experience, as well as for noviceprogrammers Those coming from another language may have
a slight advantage, but I've tried to provide an on-ramp forbeginners as well, by defining all terms, demonstrating the
relationships among the various constructs, and reviewing keyconcepts along the way
Trang 16so forth)
Chapter 5, Branching
Shows how to create programs that branch based on
Trang 17Chapter 6, Object-Oriented Programming
Explains the principles behind object-oriented programming,including encapsulation, specialization, and polymorphism
Chapter 7, Classes and Objects
Introduces the key concepts of programmer-defined types(classes) and instances of those types (objects) Classesand objects are the building blocks of object-oriented
Trang 18Explores two of the key concepts behind object-orientedprogramming, inheritance and polymorphism, and
demonstrates how you might implement them in your code
Chapter 12, Operator Overloading
Explains how to add standard operators to the types youdefine
Chapter 16, Throwing and Catching Exceptions
Trang 19Chapter 17, Delegates and Events
Discusses how to write code to respond to programmingoccurrences like mouse clicks, keystrokes, and other
events, through the use of delegates and the event
keyword
Chapter 18, Creating Windows Applications
Shows you how to bring all these skills to bear to create aWindows application
Trang 20The following font conventions are used in this book:
Italic
Used for pathnames, filenames, program names, Internetaddresses (such as domain names and URLs), and newterms where they are defined
Constant Width
Used for command lines and options that should be typedverbatim, C# keywords, and code examples
Constant Width Italic
Used for replaceable items, such as variables or optionalelements, 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 thefollowing icons:
This is a tip It contains useful supplementary information about the topic at hand.
Trang 21This is a warning It helps you solve and avoid annoying problems.
Trang 22This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Learning C# 2005, Second Edition, by Jesse Liberty
596-10209-7."
and Brian MacDonald Copyright 2006 O'Reilly Media, Inc., 0-If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
Trang 23I provide ongoing support for my books through my web site(click on "books"):
Trang 24We have tested and verified the information in this book to thebest of our ability, but you may find that features have changed(or even that we have made mistakes!) Please let us know
about any errors you find, as well as your suggestions for futureeditions, by writing to:
http://www.oreilly.com/catalog/learncsharp2
You can also send messages electronically To be put on themailing list or request a catalog, send email to:
info@oreilly.com
To comment on the book, send email to:
bookquestions@oreilly.com
For more information about this book and others, as well asadditional technical articles and discussion on the C# and the.NET Framework, see the O'Reilly web site:
http://www.oreilly.com
and the O'Reilly NET DevCenter:
Trang 25ONDotnet.com provides independent coverage of fundamental,interoperable, and emerging Microsoft NET programming andweb services technologies
Trang 26When you see a Safari® Enabled icon on the cover ofyour favorite technology book, that means the book is availableonline through the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top tech books,cut and paste code samples, download chapters, and find quickanswers when you need the most accurate, current information.Try it for free at http://safari.oreilly.com
Trang 27
Jesse Liberty
John Osborn signed me to O'Reilly, for which I will forever be inhis debt William Hamilton and Nicholas Paldino helped makethis book better than what I'd written Rob Romano created anumber of the illustrations and improved the others Tim
O'Reilly provided support and resources
Special thanks are due to my co-author, Brian MacDonald, whomade this book far superior to what I'd originally written
Brian MacDonald
First and foremost, thanks to Jesse for giving me the
opportunity to participate in this book Many thanks also toJohn Osborn, for getting me involved with O'Reilly in the firstplace Finally, thanks to my wife, Carole, who provided bothmoral support and technical assistance
Trang 28Programming C# by Jesse Liberty (O'Reilly, 2005) a more appropriate
fit for their skills.
This brief introduction will show you how C# fits into the NETpicture, what you can do with the language, and what benefitsthis language has over its predecessors
Unless otherwise specified, when we refer to C#, we mean C# 2005;
when we refer to NET, we mean the NET 2005 (.NET 2.0) Framework; and when we refer to Visual Studio, we mean Visual Studio 2005.
Finally, when we refer to using Visual Studio 2005, you may well be using Visual C# 2005 Express instead.
In the following pages, you will also learn some of the conceptsintegral to object-oriented programming, which has
revolutionized how web and Windows applications are
developed Object-oriented programming is closely tied to thesemantics of the C# language; that is, the meaning behind the
Trang 29understanding of the syntax of the C# language, but you alsoneed to understand what you are actually trying to accomplish.This book will explain it all, in the context of creating
applications to run either on the Web or on a Windows desktop
Trang 30In the past, you might have learned a language like C or Javawithout much concern about the platform on which you would
be programming These cross-platform languages were as
comfortable on a Unix box as they were on a PC running
Windows
C#, however, was created specifically for NET Although NETmay become cross-platform some day soonthere already exists
a working open-source Unix versionfor now, the overwhelmingmajority of NET programs will be written to run on a machinerunning one of the Windows operating systems
Trang 31When Microsoft announced C# 1.0 in July 2000, its unveilingwas part of a much larger event: the announcement of the NETplatform The NET platform is a development framework thatprovides a new way to create Windows applications However,.NET goes beyond traditional Windows programming to facilitatecreating web applications quickly and easily
Microsoft reportedly devoted 80% of its research and
development budget to NET and its associated technologies.The results of this commitment were very impressive In 2005,Microsoft rolled out Version 2 of the language, the platform, andthe tools Their goal was to radically reduce the amount of
boilerplate code you have to write, and to make the creation ofweb and desktop applications easier by "encapsulating" much ofthe "plumbing" of a typical application in objects
That means that rather than writing a lot of the code to connect
to databases, the Internet, or your filesystem, NET providesfully tested controls that you can drag onto your form, and theywill do all the heavy lifting for you
The scope of NET is huge The platform consists of three
separate product groups:
A set of languages, including C# and Visual Basic 2005; aset of development tools, including Visual Studio 2005; andpowerful tools for building applications, including the
Common Language Runtime (CLR), a platform for
compiling, debugging, and executing NET applications
A set of NET Enterprise Servers, including SQL Server
2005, Exchange, BizTalk, and so on, that provide specializedfunctionality for relational data storage, email, B2B
Trang 32New NET-enabled non-PC devices, from cell phones togame boxes
Trang 33
Central to the NET platform is a development environment
known as the NET Framework The Framework specifies how
.NET programming constructs such as intrinsic types, classes,and interfaces are implemented You will learn about theseconstructs in the chapters ahead
The NET Framework sits on top of any flavor of the Windowsoperating system The most important components of theFramework are the Common Language Runtime (CLR),
described in the preceding section, and 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 7
Detailed coverage of all the FCL classes is beyond the scope of this
book For more information, see C# in a Nutshell (O'Reilly) and the
MSDN Library ( http://msdn.microsoft.com/library ).
Trang 34Anders Hejlsberg and Scott Wiltamuth, developed the originalC# language Hejlsberg is also known for creating Turbo Pascal, a popular language for PC programming, and for leading theteam that designed Borland Delphi , one of the first successfulIntegrated Development Environments for client/server
programming
The goal of C# is to provide a simple, safe, object-oriented,Internet-centric, high-performance language for NET
development C# is simple 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 the language is type-safe, an
important mechanism to help you find bugs early in the
development process This makes for code that is easier to
maintain and programs that are more reliable C# 2005 wasenhanced in many ways, one of which was to add support for
Trang 35applications
C# was designed, from the very start, to support object-oriented programming This book will explain not only how towrite object-oriented programs, but also why object-orientedprogramming has become so popular The short answer is this:programs are becoming increasingly complex, and object-
oriented programming techniques help you manage that
complexity
C# was designed for NET, and NET was designed for
developing web and web-aware programs The Internet is aprimary resource in most NET applications
Trang 36At 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 nospecial characters into the file to support formatting, only thetext A classic text editor is Notepad
Example 1-1 shows an example of a very simple source codefile
charactersjust the normal text produced by your keyboard
Once you write your program in an editor, you must compile it.For that, you need a compiler (explained shortly) Once
compiled, your program must be run and tested
Although you can perform all of these tasks using Notepad (or
Trang 372005 development environment
The overwhelming majority of C# programmers will be building Windows and web applications for the NET platform using the Visual Studio 2005, and all the examples for this book have been tested in that environment.
A free version of this popular product, called Visual C# 2005 Express Edition, is available for download at
http://msdn.microsoft.com/vstudio/express/visualcsharp/ There are excellent open source C# compilers available, such as those from the Mono project ( http://www.mono-project.com ) and
SharpDevelop ( http://www.icsharpcode.net/OpenSource/SD/ ).
Everything in this book should work with those compilers, but we have not tested with them and can not guarantee 100% compatibility.
Trang 38
The Visual Studio 2005 Integrated Development Environment
(IDE) provides enormous advantages to the C# programmer.
This book tacitly assumes that you'll use Visual Studio 2005 foryour work However, the discussion focuses more on the
language and the platform than on the tools
Nonetheless, Chapter 2 provides an introduction to the IDE insome detail Chapter 9 returns to the IDE to examine the
debugger, which will help you find and correct problems in yourcode
This book will focus primarily on the basics of the C# language,using simple console applications for most of the examples, toillustrate language fundamentals The last two chapters will
show you how to use C# within the context of building Windowsand web applications, respectively
Trang 39developed to allow NET programmers to create very large,
powerful, high-quality web applications quickly and easily The.NET technology for creating web applications and web services
is called ASP.NET.
Typically, you'll create an ASP.NET application when you wantyour program to be available to end users on any platform
(e.g., Windows , Mac, Unix) By serving your application overthe Web, end users can access your program with any browser
When you want the richness and power of a native applicationrunning directly on the Windows platform, you will create a
desktop Windows application The NET tools for building
Windows applications are called Windows Forms
However, if you don't need a Graphical User Interface (GUI) andjust want to write a simple application that writes to a consolewindow (i.e., what we used to call a DOS box), you might
consider creating a console application This book makes
extensive use of console applications to illustrate the basics ofthe C# language
Console applications
A console application runs in a console window, as shown in
Figure 1-1 A console window (or DOS box) provides simpletext-based output Console applications are very helpfulwhen learning a language because they strip away the
distraction of the Graphical User Interface Rather than
spending your time creating complex windowing
applications, you can focus on the details of the languageconstructs, such as how you create classes and methods,how you branch based on runtime conditions, and how youloop All these topics will be covered in detail in later
chapters
Trang 40Windows applications
A Windows application runs on a PC's desktop You are
already familiar with Windows applications such as MicrosoftWord or Excel Windows applications are much more
simple ASP.NET application
Figure 1-2 A Windows application