About this Book

This is a book about C# from version 2 onwards—it’s as simple as that. I barely cover C# 1, and only cover the .NET Framework libraries and Common Language Runtime (CLR) when they’re related to the language. This is a deliberate decision, and the result is quite a different book from most of the C# and .NET books I’ve seen.

By assuming a reasonable amount of knowledge of C# 1, I avoid spending hundreds of pages covering material that I think most people already understand. This gives me much more room to expand on the details of C# 2, 3, and 4, which is what I hope you’re reading the book for.

I believe that many developers would be less frustrated with their work if they had a deeper connection with the language they’re writing in. I know it sounds geeky in the extreme to talk about having a “relationship” with a programming language, but that’s the best way I can describe it. This book is my attempt to help you achieve that sort of understanding, or deepen it further. It won’t be enough on its own—it should be a companion to your coding, guiding you and suggesting some interesting avenues to explore, as well as explaining why your code behaves the way it does.

Who should read this book?

I’ve been very pleasantly surprised at the community reaction to the first edition of this book. I’ve seen it recommended in various places, especially on Stack Overflow (where I admit my presence might encourage a little bias). It’s usually recommended for those who wish to really know what’s going on in their code... but occasionally it’s suggested as a learning tool for beginners too. On its own, I think that’s a little bit unfortunate. You could probably struggle through, looking up C# 1 concepts as and when you needed to—but you’d be much better off reading this book in conjunction with another which starts from scratch.

Without wishing to dissuade you from buying this book if you haven’t already, there are plenty of other good C# books on the market—and they actually work well as companions to this one. I’ve seen numerous reports of readers who have started off with a book which makes fewer assumptions, and then gradually added C# in Depth to the mix. I’m happy to recommend C# 4.0 in a Nutshell (O’Reilly, 2010) as one possible choice here: it not only covers C# from scratch, but also digs into the core of the .NET Framework.

I’m not going to claim that reading this book will make you a fabulous coder. There’s so much more to software engineering than knowing the syntax of the language you happen to be using. I give some words of guidance (rather more in this second edition than in the first), but ultimately there’s a lot more gut instinct in development than most of us would like to admit. What I will claim is that if you read and understand this book, you should feel comfortable with C#, and free to follow your instincts without too much apprehension. It’s not about being able to write code that no one else will understand because it uses unknown corners of the language: it’s about being confident that you know the options available to you, and know which path the C# idioms are encouraging you to follow.

Roadmap

The book’s structure is simple. There are four parts and three appendixes. The first part serves as an introduction, including a refresher on topics in C# 1 that are important for understanding C# 2 and 3, and that are often misunderstood. The second part covers the new features in C# 2. The third part covers the new features in C# 3. I’ll leave it as an exercise to the reader to guess what the fourth part contains.

There are occasions where organizing the material this way means we come back to a topic a couple of times—in particular delegates are improved in C# 2 and then again in C# 3—but there’s method in my madness. I anticipate that a number of readers will be using different versions for different projects: for example, you may be using C# 3 at work, but experimenting with C# 4 at home. That means that it’s useful to clarify what is in which version. It also provides a feeling of context and evolution—it shows how the language has developed over time.

Chapter 1 sets the scene by taking a simple piece of C# 1 code and evolving it, seeing how later versions allow the source to become more readable and powerful. We look at the historical context in which C# has grown, and the technical context in which it operates as part of a complete platform: C# as a language builds on framework libraries and a powerful runtime to turn abstraction into reality.

Chapter 2 looks back at C# 1, and three specific aspects: delegates, the type system characteristics, and the differences between value types and reference types. These topics are often understood “just well enough” by C# 1 developers, but as C# has evolved and developed them significantly, a solid grounding is required in order to make the most of the new features.

Chapter 3 tackles the biggest feature of C# 2, and potentially the hardest to grasp: generics. Methods and types can be written generically, with type parameters standing in for real types which are specified in the calling code. Initially it’s as confusing as this description makes it sound, but once you understand generics you’ll wonder how you survived without them.

If you’ve ever wanted to represent a null integer, chapter 4 is for you. It introduces nullable types, a feature built on generics and taking advantage of support in the language, runtime, and framework.

Chapter 5 shows the improvements to delegates in C# 2. You may have only used delegates for handling events such as button clicks before now. C# 2 makes it easier to create delegates, and library support makes them more useful for situations other than events.

In chapter 6 we examine iterators, and the easy way to implement them in C# 2. Few developers use iterator blocks, but as LINQ to Objects is built on iterators, they’ll become more and more important. The lazy nature of their execution is also a key part of LINQ.

Chapter 7 shows a number of smaller features introduced in C# 2, each making life a little more pleasant. The language designers have smoothed over a few rough places in C# 1, allowing more flexible interaction with code generators, better support for utility classes, more granular access to properties, and more.

Chapter 8 once again looks at a few relatively simple features—but this time in C# 3. Almost all the new syntax is geared toward the common goal of LINQ but the building blocks are also useful in their own right. With anonymous types, automatically implemented properties, implicitly typed local variables, and greatly enhanced initialization support, C# 3 gives a far richer language with which your code can express its behavior.

Chapter 9 looks at the first major topic of C# 3—lambda expressions. Not content with the reasonably concise syntax we saw in chapter 5, the language designers have made delegates even easier to create than in C# 2. Lambdas are capable of more—they can be converted into expression trees: a powerful way of representing code as data.

In chapter 10 we examine extension methods, which provide a way of fooling the compiler into believing that methods declared in one type actually belong to another. At first glance this appears to be a readability nightmare, but with careful consideration it can be an extremely powerful feature—and one which is vital to LINQ.

Chapter 11 combines the previous three chapters in the form of query expressions, a concise but powerful way of querying data. Initially we concentrate on LINQ to Objects, but see how the query expression pattern is applied in a way which allows other data providers to plug in seamlessly.

Chapter 12 is a quick tour of various different uses of LINQ. First we see the benefits of query expressions combined with expression trees: showing how LINQ to SQL is able to convert what appears to be normal C# into SQL statements. We then move on to see how libraries can be designed to mesh well with LINQ, taking LINQ to XML as an example. Parallel LINQ and Reactive Extensions show two alternative approaches to in-process querying, and we close the chapter with a discussion of how you can extend LINQ to Objects with your own LINQ operators.

Our coverage of C# 4 begins in chapter 13, where we look at named arguments and optional parameters, COM interop improvements, and generic variance. In some ways these are very separate features, but named arguments and optional parameters contribute to COM interop as well as the more specific abilities which are only available when working with COM objects.

Chapter 14 describes the single biggest feature in C# 4: dynamic typing. The ability to bind members dynamically at execution time instead of statically at compile time is a huge departure for C#, but it is applied selectively: only code which involves a dynamic value will be executed dynamically.

Chapter 15 is about one potential future of C# code, rather than a new feature of the language itself. We look at Code Contracts, a new set of libraries and tools from Microsoft which allow you to express much more detail about what your methods need and what they’re willing to guarantee than the type system itself can. It’s early days, but it’s possible that in a few years, you wouldn’t dream of writing new code without specifying its contracts.

We wind down in chapter 16 by thinking about where we’ve come from, the current state of the industry, and what the future might hold.

The appendixes are all reference material really. In appendix A, I cover the LINQ standard query operators, with some examples. Appendix B looks at the core generic collection classes and interfaces, including the new concurrent collections in .NET 4. Appendix C provides a brief look at the different versions of .NET, including the different flavors such as the Compact Framework and Silverlight.

Terminology and typography

Most of the terminology of the book is explained as it goes along, but there are a few definitions that are worth highlighting here. I use C# 1, C# 2, C# 3, and C# 4 in a reasonably obvious manner—but you may see other books and websites referring to C# 1.0, C# 2.0, C# 3.0, and C# 4.0. The extra “.0” seems redundant to me, which is why I’ve omitted it—I hope the meaning is clear.

I’ve appropriated a pair of terms from a C# book by Mark Michaelis. To avoid the confusion between runtime being an execution environment (as in “the Common Language Runtime”) and a point in time (as in “overriding occurs at runtime”), Mark uses execution time for the latter concept, usually in comparison with compile time. This seems to me to be a thoroughly sensible idea, and one that I hope catches on in the wider community. I’m doing my bit by following his example in this book.

I frequently refer to the language specification or just the specification—unless I indicate otherwise, this means the C# language specification. However, multiple versions of the specification are available, partly due to different versions of the language itself and partly due to the standardization process. Any section numbers provided are from the C# 4.0 language specification from Microsoft.

This book contains numerous pieces of code, which appear in a fixed-width font like this; output from the listings appears in the same way. Code annotations accompany some listings, and at other times particular sections of the code are highlighted in bold. Almost all of the code appears in snippet form, allowing it to stay compact but still runnable—within the right environment. That environment is Snippy, a custom tool that’s introduced in section 1.7. Snippy is available for download, along with all of the code from the book (in the form of snippets, full Visual Studio solutions, or more often both) from the book’s website at csharpindepth.com.

Source code downloads

The source code for all of the examples from the book is available from the publisher’s website at www.manning.com/CSharpinDepthSecondEdition and from csharpindepth.com.

Author Online and the C# in Depth website

Purchase of C# in Depth, Second Edition includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and other users. To access the forum and subscribe to it, point your web browser to www.manning.com/CSharpinDepthSecondEdition. This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum.

The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.

In addition to Manning’s own website, I have set up a companion website for the book at csharpindepth.com, containing information that didn’t quite fit into the book, downloadable source code for all the listings in the book, and links to other resources.

About the author

I’m not a typical C# developer, I think it’s fair to say. For the last two years, almost all of my time working with C# has been for fun—effectively as a somewhat obsessive hobby. At work, I’ve been writing server-side Java in the Mobile team in Google London—and I can safely claim that few things help you to appreciate new language features than having to code in a language which doesn’t have them, but is similar enough to remind you of their absence.

I’ve tried to keep in touch with what other developers find hard about C# by keeping a careful eye on Stack Overflow, posting oddities to my blog, and occasionally talking about C# and related topics just about anywhere that will provide people to listen to me. In short, C# is still coursing through my veins as strongly as ever.

For all these oddities—and despite my ever-surprising micro-celebrity status due to Stack Overflow—I’m a very ordinary developer in many other ways. I write plenty of code which makes me grimace when I come back to it. My unit tests don’t always come first...and sometimes they don’t even exist. I make off-by-one errors every so often. The type inference section of the C# specification still confuses me, and there are some uses of Java wildcards which make me want to have a little lie down. I’m a deeply flawed programmer.

That’s the way it should be. For the next few hundred pages, I’ll try to pretend otherwise: I’ll espouse best practices as if I always followed them myself, and frown on dirty shortcuts as if I’d never dream of taking them. Don’t believe a word of it. The truth of the matter is, I’m probably just like you. I happen to know a bit more about how C# works, that’s all...and even that state of affairs will only last until you’ve finished the book.

About the cover illustration

The caption on the illustration on the cover of C# in Depth, Second Edition is a “Musician.” The illustration is taken from a collection of costumes of the Ottoman Empire published on January 1, 1802, by William Miller of Old Bond Street, London. The title page is missing from the collection and we have been unable to track it down to date. The book’s table of contents identifies the figures in both English and French, and each illustration bears the names of two artists who worked on it, both of whom would no doubt be surprised to find their art gracing the front cover of a computer programming book...two hundred years later.

The collection was purchased by a Manning editor at an antiquarian flea market in the “Garage” on West 26th Street in Manhattan. The seller was an American based in Ankara, Turkey, and the transaction took place just as he was packing up his stand for the day. The Manning editor didn’t have on his person the substantial amount of cash that was required for the purchase and a credit card and check were both politely turned down. With the seller flying back to Ankara that evening the situation was getting hopeless. What was the solution? It turned out to be nothing more than an old-fashioned verbal agreement sealed with a handshake. The seller simply proposed that the money be transferred to him by wire and the editor walked out with the bank information on a piece of paper and the portfolio of images under his arm. Needless to say, we transferred the funds the next day, and we remain grateful and impressed by this unknown person’s trust in one of us. It recalls something that might have happened a long time ago.

We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by the pictures from this collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.206.25