Preface

Microsoft unveiled the .NET Framework in 2000, and in the decade that followed, it became an extremely popular choice for developing software for Windows. While .NET supports many programming languages, it is most strongly associated with the language designed specifically for the platform: C#.

C# has grown considerably since its launch. Each new version enabled new programming techniques—C# 2.0 added generics and enhanced functional programming capabilities, then integrated query features and yet more powerful functional capabilities arrived in C# 3.0, and now C# 4.0 adds new dynamic language capabilities.

The .NET Framework has grown with the language. Back in .NET 1.0, the class libraries offered relatively patchy coverage of the underlying Windows capabilities. Moreover, the library features that were unique to .NET, rather than being wrappers for something else, were relatively modest. Now, as well as more comprehensive platform coverage we have a GUI framework (WPF), much stronger database capabilities, powerful support for concurrent execution, and an extensive set of communication services (WCF), to name just a few of the available features. And the features that have been there since version 1.0, such as web support (ASP.NET), have been fleshed out substantially.

.NET is no longer limited to running just on Windows. Some people recognized its potential for platform independence early on, but for years, Microsoft supported C# just on Windows, leaving open source projects to offer the only way to run C# on other systems. But in 2008, the release of Silverlight 2 saw C# code running with Microsoft’s full support on non-Windows platforms such as the Mac for the first time.

The C# language has come a long way since 2000, in both reach and size. Our goal with Programming C# 4.0 is to show how to use C#.

How This Book Is Organized

The book begins by looking at the details of the C# language that you will use in everyday programming. We then look at the most common parts of the .NET Framework class library that you will also use very regularly. Next, we move into some more specialized areas of the framework. Finally, we look at some of the application frameworks for building Windows and web applications in .NET.

Chapter 1, Introducing C#

This chapter talks about the nature of C# and its relationship with the .NET Framework.

Chapter 2, Basic Programming Techniques

In this chapter, we show the core elements of C# code—the steps required to get up and running, and fundamental features such as variables, flow control, loops, and methods.

Chapter 3, Abstracting Ideas with Classes and Structs

C# supports object-oriented programming, and this chapter describes the language features dedicated to these techniques.

Chapter 4, Extensibility and Polymorphism

This chapter continues the discussion from the preceding chapter, illustrating how C# supports inheritance, interfaces, and related concepts.

Chapter 5, Composability and Extensibility with Delegates

C# isn’t limited to object-oriented programming—it also supports some very powerful functional programming idioms. This chapter shows how these can sometimes be more flexible and also simpler than OO techniques.

Chapter 6, Dealing with Errors

All programs encounter failures, whether due to programming errors, unexpected input, network failures, or a host of other eventualities. This chapter shows the options for detecting and responding robustly to errors.

Chapter 7, Arrays and Lists

This chapter shows the tools C# offers for representing simple collections of information.

Chapter 8, LINQ

It’s not enough merely to be able to represent collections, so this chapter shows how you can use the integrated query features in C# to process your collections of data.

Chapter 9, Collection Classes

This chapter shows some of the more specialized classes for working with collections in particular ways.

Chapter 10, Strings

Text is a particularly important data type for most applications, so this chapter shows how text is represented, and how you can format data into textual form.

Chapter 11, Files and Streams

This chapter shows how to store information on disk and read it back in, and how to perform other filesystem operations. It also shows how some of the abstractions used when working with files can be applied in other scenarios.

Chapter 12, XML

This chapter shows the classes offered by the .NET Framework for processing XML, and how these can work in conjunction with the LINQ features in C#.

Chapter 13, Networking

In this chapter, we look at the various techniques for communicating over a network.

Chapter 14, Databases

This chapter shows how to access a database from C#.

Chapter 15, Assemblies

In this chapter, we show how to compile code into libraries for reuse, and how programs made up from multiple components work.

Chapter 16, Threads and Asynchronous Code

Many programs need to deal with concurrency, and this chapter shows the tools and techniques available.

Chapter 17, Attributes and Reflection

C# has the ability to inspect the structure of code, which makes it easier to automate certain kinds of tasks. This chapter shows the API for doing this, and how you can extend the structural information through attributes.

Chapter 18, Dynamic

One of the new features in C# 4.0 is support for dynamic binding. This is particularly useful in certain interop scenarios, as we discuss in this chapter.

Chapter 19, Interop with COM and Win32

Sometimes it’s necessary for C# code to communicate with components not designed to be used from .NET. This chapter shows how to do this with both COM components and Win32-style DLLs.

Chapter 20, WPF and Silverlight

WPF and Silverlight offer very similar programming models for building user interfaces. This chapter shows how to use that model from C#.

Chapter 21, Programming ASP.NET Applications

This chapter shows how to use ASP.NET, the part of the .NET Framework designed for building web applications.

Chapter 22, Windows Forms

This chapter shows how to use Windows Forms, which is a wrapper around the classic Windows user interface mechanisms. While it is less flexible than WPF, it can offer an easier way to integrate with old components such as ActiveX controls.

Where to Find Features New in C# 4.0 and .NET 4

Although this book is written to be read as a whole, we expect that some readers will want to look for the features new to C# 4.0, and also to .NET 4. Since our goal is to show how the C# language is used today, we have avoided structuring the book around the history of the language, because you will use language features of varying ages in combination. As it happens, one of the new features in C# 4.0 serves a very specific purpose, so it gets its own chapter, but for the most part, new language features are spread throughout the book, because we aim to mention them where you need to know about them. We cannot point you at a particular set of chapters, so instead, here’s a quick guide to where we discuss these features.

Chapter 1 talks about the broad goals behind the new features in C# 4.0. Chapter 3 shows the use of default values and named arguments (and these come up again very briefly in Chapters 11 and 17). Chapter 7 describes variance, a rather technical feature of the type system that has some useful implications for collection types. Chapter 16 talks about the extensive new multithreading support added in .NET 4. Chapter 18 is dedicated entirely to a new language feature: support for dynamic programming. Chapter 19 describes the new no-PIA feature, and some features that allow more elegant code in some interop scenarios.

Who This Book Is For

If you have some basic knowledge of C# but want to brush up your skills, or if 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.

What You Need to Use This Book

To make the best use of this book, please obtain the latest release of Visual Studio 2010. Any edition will do, including the free Express edition for C#, which can be downloaded from http://www.microsoft.com/express/.

For Chapter 14 you will need a copy of SQL Server or SQL Server Express. Some editions of Visual Studio will install SQL Server Express for you by default, so you may already have this.

The example source code for this book is available through the O’Reilly site at http://oreilly.com/catalog/9780596159832/.

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:

Note

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.

Using Code Examples

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# 4.0, Sixth Edition, by Ian Griffiths, Matthew Adams, and Jesse Liberty. Copyright 2010 Ian Griffiths and Matthew Adams, 978-0-596-15983-2.”

Safari® Books Online

Note

Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.

With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.

O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com/?portal=oreilly.

Acknowledgments

From Ian Griffiths

I want to thank the technical reviewers, whose feedback helped to improve this book: Nicholas Paldino, Chris Smith, Chris Williams, Michael Eaton, Brian Peek, and Stephen Toub.

Everyone at O’Reilly has provided a great deal of support and patience throughout the project, so many thanks to Mike Hendrickson, Laurel Ruma, Audrey Doyle, and Sumita Mukherji. Thanks also to John Osborn for getting things started in the early days of this project, and for getting Matthew and me on board as O’Reilly authors in the first place, all those years ago.

Thank you to my coauthor for not learning his lesson from the last book and agreeing to write another with me. And finally, thank you to Jesse Liberty for asking us to take over his book.

From Matthew Adams

I’d like to add my thanks to those of my coauthor to all those at O’Reilly whose patience, help, and support have made this book possible, and to all our reviewers whose feedback has been invaluable.

In addition, I’d like to add a nod to Karolina Lemiesz, coffee wizard at the Starbucks where most of my text was written, for the constant supply of ristretto, and an education in coffee tasting when work got too much.

As always, my partner Una provided the necessary foundation of love and support (despite her own book deadlines). And finally, anyone who tells you that squeezing a book out of an author is a breeze is clearly deluded, but my coauthor makes it look easy. My thanks go to him especially for his forbearance, wit, and friendship. And good dinners.

Get Programming C# 4.0, 6th 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.