In 2000, .NET revolutionized the way we create both web and Windows applications. .NET 2.0 was a dramatic incremental improvement over .NET 1.0. This book covers C# 3.0 and .NET 3.5, and this time we are looking at an even more significant set of changes.
C# 3.0 introduces a new generation of changes to a framework that takes an enormous leap forward, revolutionizing the way we program Windows applications, web services, and, to a lesser degree, web applications.
In 2000, I wrote in the first edition of this book that Microsoft had "bet the company" on .NET. It was a good bet. In 2007, I bet my career on .NET by joining Microsoft as senior program manager in the Silverlight Development Division.
Because one way (my preferred way) to program Silverlight is with C#, I have the opportunity to stay very current with this mature yet rapidly evolving language. It is an exciting time for C#; version 3.0 adds a number of tremendously useful features, and the newest edition of Visual Studio makes programming with these features easier than ever.
It is my goal that you'll find Programming C# 3.0 to be of great use whether this is your first exposure to .NET programming, or you've been at it for some time. I'll start with the fundamentals, and introduce new additions to the language not as obscure add-ons, but as the integrated features that they are.
If you are already a C# 2.0 programmer, feel free to skim through the parts you know. The new features are called out by appropriate headings; you won't inadvertently skip over them. But be sure to reread Chapter 12, and all of Part II and Part III.
The programming language of choice for .NET is C#, which builds on the lessons learned from C (high performance), C++ (object-oriented structure), Java™ (garbage collection, high security), and Visual Basic (rapid development) to create a language ideally suited for developing component-based, n-tier, distributed Windows client and web applications.
This book is a tutorial, both on C# and on writing .NET applications with C#.
If you are a proficient C# 2.0 programmer, and all you want to know is what is new in C# 3.0, put this book down, buy Programming .NET 3.5 by myself and Alex Horovitz (O'Reilly), and then read a lot about Language-Integrated Query (LINQ). You'll get by.
If, on the other hand, you want to brush up on your C# skills, or you are proficient in another programming language such as C++ or Java, or even if C# is your first programming language, this book is for you.
Note that for this edition I have been joined by a second author: Donald Xie. Donald and I have worked together on a number of books for the past decade. He is smart, diligent, and careful, and much of the work of this book is his, but every word in this book is mine. Donald wrote and rewrote much of the new material, but he did so knowing that I would then rewrite it so that this book speaks with a single voice. I think it is imperative for a tutorial such as this to speak from the mind of a single developer (me) into the mind of another developer (you) with as little distortion as possible.
To make the best use of this book, please obtain the latest release of Visual Studio 2008. Any edition will do, including the Express edition for C#.
For Chapter 16, you will want to ensure that SQL Server or SQL Server Express is installed (it is normally installed automatically with Visual Studio), and you'll want to install the (old) Northwind database that was created for SQL Server 2000, but which works fine with the latest SQL Server editions.
To run the Windows Presentation Foundation (WPF) example in Chapter 18, you'll need to be running Vista, or you'll need to download the .NET 3.5 runtime.
All of this is available on the Microsoft web site, at no cost. Go to http://www.microsoft.com and type "C# Express" into the search window. The first or second link should take you to the download page.
The source code for every example in this book is available through the O'Reilly site, http://www.oreilly.com/catalog/9780596527433, or through my portal site: http://www.JesseLiberty.com. Please scroll to and click on the book site, then click on Books and scroll to this book, and you should find a link to the source code.
In addition, I provide a private, free support forum for all my writing, which you can also access through the portal.
The C# Language focuses on the details of the language, Part II examines how C# supports interacting with data, Part III discusses how to write .NET programs, and Part IV describes how to use C# with the .NET Common Language Runtime (CLR) and Framework Class Library (FCL).
This chapter demonstrates a simple program to provide a context for what follows, and introduces you to the Visual Studio integrated development environment (IDE) and a number of C# language concepts.
This chapter presents the basics of the language, from built-in datatypes to keywords.
Classes define new types and allow programmers to extend the language so that they can better model the problems they're trying to solve. This chapter explains the components that form the heart and soul of C#.
Classes can be complex representations and abstractions of things in the real world. This chapter discusses how classes relate and interact.
This chapter teaches you how to add operators to your user-defined types.
This chapter introduce structs, which are lightweight objects that are more restricted than classes and that make fewer demands on the operating system and on memory.
Interfaces, the subject of Chapter 8, are contracts: they describe how a class will work so that other programmers can interact with your objects in well-defined ways.
Object-oriented programs can create a great many objects. It is often convenient to group these objects and manipulate them together, and C# provides extensive support for collections. This chapter explores the collection classes provided by the FCL, the new Generic collections, and how to create your own collection types using Generics.
This chapter discusses how you can use C# to manipulate text strings and regular expressions. Most Windows and web programs interact with the user, and strings play a vital role in the user interface.
This chapter explains how to deal with exceptions, which provide an object-oriented mechanism for handling life's little emergencies.
Both Windows and web applications are event-driven. In C#, events are first-class members of the language. This chapter focuses on how events are managed and how delegates (object-oriented, type-safe callback mechanisms) are used to support event handling.
This chapter introduces LINQ, a new technology in C# for interacting with data from any data source, including relational databases, XML, files, and other nontraditional data sources.
This chapter is a brief tutorial on XML, the lingua franca of .NET programming.
This chapter returns to LINQ and dives deeper into interacting with SQL and XML data in your C# programs.
This chapter demonstrates the use of the .NET Framework's ADO.NET object model, designed to provide access to relational data from objects.
On top of the .NET infrastructure sits a high-level abstraction of the operating system, designed to facilitate object-oriented software development. This top tier includes ASP.NET and Windows applications. ASP.NET (with AJAX) is one of the world's most popular ways to create web applications. Although C# is a standalone programming language, it is my premise that the vast majority of the readers of this book are learning C# to build .NET applications.
This chapter demonstrates how to build an ASP.NET application and use C# to handle events.
This chapter is a crash course in building a nontrivial WPF application, with a focus on using C# to create event handlers.
This chapter demonstrates how to build a significant Windows Forms application, again using C# for event handling.
Part IV of this book discusses the relationship of C# to the CLR and the FCL.
.NET assemblies include extensive metadata about classes, methods, properties, events, and so forth. This metadata is compiled into the program and retrieved programmatically through reflection. This chapter explores how to add metadata to your code, how to create custom attributes, and how to access this metadata through reflection. It goes on to discuss dynamic invocation, in which methods are invoked with late (runtime) binding.
The FCL provides extensive support for asynchronous I/O and other classes that make explicit manipulation of threads unnecessary. However, C# does provide extensive support for threads and synchronization, discussed in this chapter.
This chapter discusses streams, a mechanism not only for interacting with the user, but also for retrieving data across the Internet. This chapter includes full coverage of C# support for serialization: the ability to write an object graph to disk and read it back again.
This chapter explores interoperability: the ability to interact with COM components that are created outside the managed environment of the .NET Framework. It's possible to call components from C# applications into COM, and to call components from COM into C#. Chapter 23 describes how this is done.
The book concludes with a glossary of C# keywords first published in C# 3.0 in a Nutshell by Joseph and Ben Albahari (O'Reilly). Whenever you encounter a keyword that you don't recognize in an example, turn first to the glossary and then to the index for further information.
Programming C# 3.0, Fifth Edition, was written for programmers who want to develop applications for the .NET platform. No doubt many of you already have experience in C++, Java, or Visual Basic (VB). Other readers may have experience with other programming languages, and some readers may have no specific programming experience but perhaps have been working with HTML and other web technologies. This book is written for all of you, though if you have no programming experience at all, you may find some of it tough going.
For a deeper exploration of the more advanced C# language elements we introduce in this book, especially LINQ, we recommend C# 3.0 in a Nutshell. C# 3.0 Cookbook by Jay Hilyard and Steve Teilhet (O'Reilly) contains more than 250 C# 3.0 solutions to common programming tasks you're likely to face on the job after you've mastered this book.
If you prefer a more structured approach to the basics of C# programming, complete with quizes and exercises to test your knowledge, I suggest you take a look at Learning C# 2005, by myself and Brian MacDonald (O'Reilly).
The following font conventions are used in this book:
Italic is used for:
Pathnames, filenames, and program names
Internet addresses, such as domain names and URLs
New terms where they are defined
Constant Width is used for:
Command lines and options that should be typed verbatim
Names and keywords in program examples, including method names, variable names, and class names
Constant Width Italic is used for:
Replaceable items, such as variables or optional elements, within syntax lines or code
Constant Width Bold is used for:
Emphasis within program code
Pay special attention to notes set apart from the text with the following icons:
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.
Please scroll down to my private web site (you'll see the word Books circled). Clicking on that image will bring you either to LibertyAssociates.com or to jliberty.com (same site). Click on Books and scroll to this book, where you will find (at a minimum) the source code, the errata (if there are any), and a FAQ (if there is one!).
Back on my portal site, you'll also find a link to my free, private support forum. Please feel free to post questions about this book or any of my writings there. The most effective way to get help is to ask a very precise question, or even to create a small program that illustrates your area of concern or confusion. You may also want to check the various newsgroups and discussion centers on the Internet. Microsoft offers a wide array of newsgroups.
If you have questions about Silverlight, please use my portal to access Silverlight.net or my Silverlight blog; if you have questions about my O'Reilly articles, please use my portal to access my O'Reilly blog, and if you have questions or comments about my politics, please use my portal to access my political blog. Keeping these things separate keeps me sane and keeps my bosses happy.
We have tested and verified the information in this book to the best 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 future editions, by writing to:
|O'Reilly Media, Inc.|
|1005 Gravenstein Highway North|
|Sebastopol, CA 95472|
|800-998-9938 (in the United States or Canada)|
|707-829-0515 (international or local)|
To comment or ask technical questions about this book, send email to:
For more information about our books, conferences, Resource Centers, and the O'Reilly Network, as well as additional technical articles and discussion on C# and the .NET Framework, see the O'Reilly web site:
and O'Reilly's ONDotnet:
This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from 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 book and 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 attribution usually includes the title, author, publisher, and ISBN. For example: "Programming C# 3.0, Fifth Edition, by Jesse Liberty and Donald Xie. Copyright 2008 O'Reilly Media, Inc., 978-0-596-52743-3."
When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O'Reilly Network Safari Bookshelf.
Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.
I want to thank the extraordinary technical editors who worked on this book: Joe Albahari, Glyn Griffiths, Jay Hilyard, Robert McGovern, and Alex Turner. Special thanks go to Ian Griffiths, who provided extensive technical editing and expertise, and is one of the nicest and smartest people on the planet.
This is the fifth edition of Programming C#, and too many friends and readers have helped me improve the book to possibly name them all. John Osborn signed me to O'Reilly, for which I will forever be in his debt, and Tim O'Reilly continues to provide an amazing independent publishing house with some of the highest standards in the industry.
And no, the authors don't get to pick the animals on the cover.
A key player in making this book a far better one than the one I wrote was Brian MacDonald; he is an amazingly talented editor and a preternaturally patient man. Without his organizational skills, his unrelenting commitment to excellence, and his unfailing good humor, this book literally would not have been possible. I must also heartily thank my coauthor Donald Xie (who helped me discover that although calling Australia by Skype may be free, calling direct for 30 minutes costs $150!), without whom this edition would not have been on the shelves before C# 4.0!
Many have written in with errata large and small for previous editions, and for that I am very grateful. We've worked hard to fix all of the mistakes, no matter how trivial. We've scoured the book to ensure that no new errors were added, and that all the code compiles and runs properly with Visual Studio 2008. With that said, if you do find errors, please check the errata on my web site (http://www.JesseLiberty.com), and if your error is new, please send me email at firstname.lastname@example.org.
Finally, in many of our examples, we use the name Douglas Adams as a tribute to and with great respect for this wonderful man, who is the author of the incredible five-part Hitchhiker's Guide to the Galaxy trilogy (Del Rey), and many other wonderful books.
I really must thank Jesse for teaching me C++ 10 years ago, and for encouraging me to write. It has been a tremendous pleasure working with Jesse. I would also like to thank the dedicated people at O'Reilly: John Osborn, Brian MacDonald, Sumita Mukherji, and the technical reviewers who have worked tirelessly to make this book possible.
This book is dedicated to those who come out, loud, and in your face and in the most inappropriate places. We will look back at this time and shake our heads in wonder. In 49 states, same-sex couples are denied the right to marry, though incarcerated felons are not. In 36 states, you can legally be denied housing just for being queer. In more than half the states, there is no law protecting LGBT children from harassment in school, and the suicide rate among queer teens is 400 percent higher than among straight kids. And, we are still kicking gay heroes out of the military despite the fact that the Israelis and our own NSA, CIA, and FBI are all successfully integrated. So, yes, this dedication is to those of us who are out, full-time.