Preface

Every 10 years or so, a new technology arrives that changes the way we think about application development. In the early 1980s, the new technologies were Unix, which could be run on a desktop, and a powerful new language called C, developed by AT&T. The early ’90s brought Windows and C++. Each development represented a sea change in the way we approached programming. In 2000, .NET and C# were the next wave, and .NET 2.0 completes the transition.

Microsoft has “bet the company” on .NET. When a company of its size and influence spends billions of dollars and reorganizes its entire corporate structure to support a new platform, programmers take notice. It turns out that .NET represents a major change in the way you’ll think about programming. It is, in short, a new development platform designed to facilitate object-oriented Internet development. The programming language of choice for this platform 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 new language ideally suited for developing component-based, n-tier distributed web applications.

C# 2.0, the language of choice for .NET 2005, comes with updated tools and a powerful new development environment. It is the crowning achievement of Microsoft’s R&D investment. It is wicked cool.

About This Book

This book is a tutorial, both on C# and on writing .NET applications with C#.

If you are a proficient C# 1.1 programmer, and all you want to know is what is new in C# 2.0, put this book down, and buy Visual C# 2005: A Developer’s Notebook (O’Reilly Media, Inc.).

If, on the other hand, you want to brush up on your C# skills, or you are proficient in another programming language like C++ or Java, or even if this is your first programming language, then this book is for you.

What You Need To Use This Book

Starting with the Beta release of Visual Studio Whidbey (2005), Microsoft has made it much easier for you to get access to their works-in-progress. There are several options available to you: just as Visual Studio comes in many flavors, the prerelease versions of .NET 2.0 and Visual Studio 2005 come in many forms:

Download the SDK

The Beta SDK, which includes command-line compilers, documentation, and other tools, is available as a free download from http://msdn.microsoft.com/netframework/downloads/updates/default.aspx. This is a small download, but you’ll need to bring your own code editor (anything from Notepad to SharpDevelop will do).

Express Editions

Microsoft has released stripped-down versions of Visual Studio that are small downloads, so you can get up and running quickly. You can download the Express Editions from http://lab.msdn.microsoft.com/vs2005/. Use Visual C# Express for most of the examples in this book. You’ll need Visual Web Developer Express for some of the examples, and you’ll need to install SQL Server Express or MSDE (Microsoft Data Engine) for some of the ADO.NET examples.

Beta and Community Tech Preview

Microsoft has also made full versions of Visual Studio 2005 available for download. These come in two forms: Community Technology Preview (CTP), which are somewhat rough around the edges, and full-fledged beta releases. At the time of this writing, CTPs is available to MSDN subscribers for Visual Studio Professional, Standard, and Team System. Beta 1 of Visual Studio Professional is also available to MSDN subscribers and to nonsubscribers for the cost of shipping. For more information, see http://lab.msdn.microsoft.com/vs2005/get/default.aspx.

Mono

The Mono Project is an open source development platform based on .NET. It’s sponsored by Novell, and runs on Linux, Mac OS X, and other operating system. Although the current version is targeted at .NET 1.1, you can choose to install it with support for some .NET 2.0 features. For more information, see http://www.mono-project.com/about/index.html.

Programming C#, Fourth Edition, will work with any of these environments. However, because each one is at a slightly different version level, some screenshots may differ from what you see. In short, your mileage may vary.

How the Book Is Organized

Part I focuses on the details of the language, Part II discusses how to write .NET programs, and Part III describes how to use C# with the .NET Common Language Runtime and Framework Class Library.

Part I, The C# Language

Chapter 1, introduces you to the C# language and the .NET platform.

Chapter 2, demonstrates a simple program to provide a context for what follows, and introduces you to the Visual Studio IDE and a number of C# language concepts.

Chapter 3, presents the basics of the language, from built-in datatypes to keywords.

Classes define new types and allow the programmer to extend the language so that he can better model the problem he’s trying to solve. Chapter 4, explains the components that form the heart and soul of C#.

Classes can be complex representations and abstractions of things in the real world. Chapter 5, discusses how classes relate and interact.

Chapter 6, teaches you how to add operators to your user- defined types.

Chapter 7 and Chapter 8 introduce Structs and Interfaces, respectively, both close cousins to classes. Structs are lightweight objects that are more restricted than classes, and that make fewer demands on the operating system and on memory. Interfaces 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. Chapter 9, explores the collection classes provided by the Framework Class Library, the new Generic collections, and how to create your own collection types using Generics.

Chapter 10, 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.

Chapter 11, 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. Chapter 12, focuses on how events are managed and how delegates (object-oriented type-safe callback mechanisms) are used to support event handling.

Part II, Programming with C#

Part II details how to write .NET programs: both desktop applications with Windows Forms and web applications with Web Forms. In addition, Part II describes database interactivity and how to create web services.

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 Forms. ASP.NET includes both Web Forms, for rapid development of web applications, and web services, for creating web objects with no user interface. A web service is a distributed application that provides functionality via standard web protocols, most commonly XML and HTTP.

C# provides a Rapid Application Development (RAD) model similar to that previously available only in Visual Basic. Chapter 13, describes how to use this RAD model to create professional-quality Windows programs using the Windows Forms development environment.

Whether intended for the Web or for the desktop, most applications depend on the manipulation and management of large amounts of data. Chapter 14, explains the ADO.NET layer of the .NET Framework and how to interact with Microsoft SQL Server and other data providers.

Chapter 15 focuses on the two parts of ASP.NET technology: Web Forms and Web Services.

Chapter 16, combines a number of the skills taught in Part II to show you how to build a set of integrated applications.

Part III, The CLR and the .NET Framework

A runtime is an environment in which programs are executed. The Common Language Runtime (CLR) is the heart of .NET. It includes a data-typing system that is enforced throughout the platform and that is common to all languages developed for .NET. The CLR is responsible for processes such as memory management and reference counting of objects.

Another key feature of the .NET CLR is garbage collection. Unlike with traditional C/C++ programming, in C# the developer isn’t responsible for destroying objects. Endless hours spent searching for memory leaks are a thing of the past; the CLR cleans up after you when your objects are no longer in use. The CLR’s garbage collector checks the heap for unreferenced objects and frees the memory used by these objects.

The .NET platform and class library extend upward to the middle-level platform, where you find an infrastructure of supporting classes, including types for interprocess communication, XML, threading, I/O, security, diagnostics, etc. The middle tier also includes the data-access components collectively referred to as ADO.NET.

Part III of this book discusses the relationship of C# to the CLR and the Framework Class Library.

Chapter 17, distinguishes between private and public assemblies and describes how assemblies are created and managed. In .NET, an assembly is a collection of files that appears to the user to be a single dynamic link library (DLL) or executable file. An assembly is the basic unit of reuse, versioning, security, and deployment.

.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. Chapter 18, 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 .NET Framework was designed to support web-based and distributed applications. Components created in C# may reside within other processes on the same machine or on other machines across the network or across the Internet. Marshaling is the technique of interacting with objects that aren’t really there, while remoting comprises techniques for communicating with such objects. Chapter 19, elaborates.

The Framework Class Library 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 Chapter 20.

Chapter 21 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.

Chapter 22, explores interoperabilitythe 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 22 describes how this is done.

The book concludes with an appendix of C# keywords.

Who This Book Is For

Programming C#, Fourth 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.

If you’re migrating from C, C++, VB 6, or Java, the following sections should give you some basic comparisons with C#. More importantly, keep an eye out for notes specifically for you throughout the book.

C# 2.0 Versus C# 1.1

There have been many changes to C# and to the development environment and the .NET Framework since 1.1. All are designed to minimize the amount of “plumbing” you have to write, and to help you focus on building robust applications.

This book integrates the changes and isn’t intended to be a guide for the proficient C# 1.1 programmer looking only for the changes in C# 2.0. That said, I do try to flag what is new in C# 2.0 as we go along.

C# Versus Visual Basic .NET

The premise of the .NET Framework is that all languages are created equal. To paraphrase George Orwell, however, some languages are more equal than others. C# is an excellent language for .NET development. You will find it is an extremely versatile, robust, and well-designed language. It is also currently the language most often used in articles and tutorials about .NET programming.

It is possible that many VB 6 programmers will choose to learn C# instead of upgrading their skills to VB.NET. The transition from VB 6 to VB.NET is, arguably, nearly as difficult as from VB 6 to C#, and, whether it’s fair or not, historically, C-family programmers have had higher earning potential than VB programmers. As a practical matter, VB programmers have never gotten the respect or compensation they deserve, and C# offers a wonderful chance to make a potentially lucrative transition.

In any case, if you do have VB experience, welcome! This book was designed with you in mind too, and I’ve tried to make the conversion easy.

C# Versus Java

Java programmers may look at C# with a mixture of trepidation, glee, and resentment. It has been suggested that C# is somehow a “rip-off” of Java. I won’t comment on the religious war between Microsoft and the “anyone but Microsoft” crowd, except to acknowledge that C# certainly learned a great deal from Java. But then Java learned a great deal from C++, which owed its syntax to C, which in turn was built on lessons learned in other languages. We all stand on the shoulders of giants.

C# offers an easy transition for Java programmers: the syntax is very similar and the semantics are familiar and comfortable. Java programmers will probably want to focus on the differences between Java and C# to use the C# language effectively. I’ve tried to provide a series of markers along the way (see the notes to Java programmers within the chapters).

C# Versus C and C++

While it is possible to program in .NET with C or C++, it isn’t easy or natural. Frankly, having worked for 10 years as a C++ programmer and written a dozen books on the subject, I’d rather have my teeth drilled than work with managed C++. Perhaps it is just that C# is so much friendlier. In any case, once I saw C#, I never looked back.

Be careful, though; there are a number of small traps along the way, and I’ve been careful to mark these with flashing lights and yellow cones.

Conventions Used in This Book

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:

Tip

This is a tip. It contains useful supplementary information about the topic at hand.

Warning

This is a warning. It helps you solve and avoid annoying problems.

Support

As part of my responsibilities as author, I provide ongoing support for my books through my web site:

http://www.LibertyAssociates.com

You can also obtain the source code for all the examples in Programming C# at my site. You will find 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) and errata files. If you check these files and still have a question, please go ahead and post to the discussion center.

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, and DevelopMentor (http://discuss.develop.com) has wonderful .NET email discussion lists.

We’d Like to Hear from You

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)
(707) 829-0104 (fax)

We have a web page for the book that lists examples and any plans for future editions. You can access this information at:

http://www.oreilly.com/catalog/progcsharp4

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:

http://www.oreilly.com

and O’Reilly’s ONDotnet:

http://www.ondotnet.com

Safari Enabled

image with no caption

When you see a Safari® Enabled icon on the cover of your favorite technology book, it 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.

Acknowledgments

Before I say anything else, I must give special thank to Ian Griffiths, who provided extensive technical editing and expertise and is one of the nicer and smarter guys around.

This is the fourth edition of Programming C#, and too many friends and readers have helped me improve the book to possibly name them all, but I must make special mention of Donald Xie, Dan Hurwitz, Seth Weiss, Sue Lynch, Cliff Gerald, Tom Petr, Jim Culbert, Mike Woodring, Eric Gunnerson, Rob Howard, Piet Obermeyer, Jonathan Hawkins, Peter Drayton, Brad Merrill, Ben Albahari, Susan Warren, Brian Bischof, and Kent Quirk.

John Osborn signed me to O’Reilly, for which I will forever be in his debt. Valerie Quercia, Claire Cloutier, and Tatiana Diaz did tremendous work on previous versions, and the upgrade to C# 2.0 was shepherded by Brian Jepson. Rob Romano created a number of the illustrations and improved the others. Tim O’Reilly provided support and resources, and I’m grateful.

Many readers have written to point out typos and minor errors in the first three editions. Their effort is very much appreciated, with special thanks to Peter Adams, Sol Bick, Brian Cassel, Steve Charbonneau, Ronald Chu, John Corner, Duane Corpe, Kevin Coupland, Randy Eastwood, Glen Fischer, Larry Fix, Andy Gaskall, Dave Fowler, Vojimir Golem, David Kindred, Steve Kirk, Bob Kline, Theron LaBounty, Aron Landy, Jeremy Lin, Chris Linton, Mark Melhado, Harry Martyrossian, Jason Mauss, Stephen Nelson, Harold Norris, Tim Noll, Mark Phillips, Marcus Rahilly, Paul Reed, Christian Rodriguez, David Solum, Paul Schwartzburg, Erwing Steininger, Fred Talmadge, Steve Thomson, Greg Torrance, Ted Volk, John Watson, Walt White, and Seen Sai Yang.

We’ve worked hard to fix all of these errors in this fourth edition. 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 2005. That said, if you do find errors, please check the errata on my web site (http://www.LibertyAssociates.com) and if your error is new, please send me email at .

Get Programming C#, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.