Essential C# 3.0: For .NET Framework 3.5

Essential C# 3.0: For .NET Framework 3.5

by Mark Michaelis

NOOK Book(eBook)

$23.49 $39.99 Save 41% Current price is $23.49, Original price is $39.99. You Save 41%.
View All Available Formats & Editions

Available on Compatible NOOK Devices and the free NOOK Apps.
WANT A NOOK?  Explore Now


Essential C# 3.0 is an extremely well-written and well-organized “no-fluff” guide to C# 3.0, which will appeal to programmers at all levels of experience with C#. This fully updated edition dives deep into the new features that are revolutionizing programming, with brand new chapters covering query expressions, lambda expressions, extension methods, collection interface extensions, standard query operators, and LINQ as a whole.


Author Mark Michaelis covers the C# language in depth, and each importantconstruct is illustrated with succinct, relevant code examples. (Complete code examples are available online.) Graphical “mind maps” at the beginning of each chapter show what material is covered and how each topic relates to the whole. Topics intended for beginners and advanced readers are clearly marked.


Following an introduction to C#, readers learn about 

  • C# primitive data types, value types, reference types, type conversions, and arrays
  • Operators and control flow, loops, conditional logic, and sequential programming
  • Methods, parameters, exception handling, and structured programming
  • Classes, inheritance, structures, interfaces, and object-oriented programming
  • Well-formed types, operator overloading, namespaces, and garbage collection
  • Generics, collections, custom collections, and iterators
  • Delegates and lambda expressions
  • Standard query operators and query expressions
  • LINQ: language integrated query
  • Reflection, attributes, and declarative programming
  • Threading, synchronization, and multithreaded patterns
  • Interoperability and unsafe code
  • The Common Language Infrastructure that underlies C# 

Whether you are just starting out as a programmer, are an experienced developer looking to learn C#, or are a seasoned C# programmer interested in learning the new features of C# 3.0, Essential C# 3.0 gives you just what you need to quickly get up and running writing C# applications.

Product Details

ISBN-13: 9780132701594
Publisher: Pearson Education
Publication date: 08/22/2008
Series: Microsoft Windows Development Series
Sold by: Barnes & Noble
Format: NOOK Book
Pages: 880
File size: 35 MB
Note: This product may take a few minutes to download.

About the Author

Mark Michaelis is an enterprise software architect at Itron Inc. In addition, Mark recently started intelliTechture, a software engineering and consulting company offering high-end consulting in Microsoft VSTS/TFS, BizTalk, SharePoint, and .NET 3.0. Mark also serves as a chief software architect and trainer for IDesign Inc.


Mark holds a B.A. in philosophy from the University of Illinois and an M.S. in computer science from the Illinois Institute of Technology. Mark was recently recognized as a Microsoft Regional Director. Starting in 1996, he has been a Microsoft MVP for C#, Visual Studio Team System, and the Windows SDK. He serves on several Microsoft software design review teams, including C#, the Connected Systems Division, and VSTS. Mark speaks at many developer conferences and has written numerous articles and books.


When not bonding with his computer, Mark is busy with his family or training for the Ironman. Mark lives in Spokane, Washington, with his wife Elisabeth, and three children, Benjamin, Hanna, and Abigail.

Table of Contents

Figures xxiii

Tables xxv

Foreword xxvii

Preface xxxi

Acknowledgments xliii

About the Author xlv


Chapter 1: Introducing C# 1

Hello, World 2

Working with Variables 12

Comments 19


Chapter 2: Data Types 31

Fundamental Numeric Types 32

More Fundamental Types 40

null and void 51

Categories of Types 55

Nullable Modifier 57

Conversions between Data Types 58

Arrays 65


Chapter 3: Operators and Control Flow 83

Operators 84

Introducing Flow Control 98

Code Blocks ({}) 105

Scope 107

Boolean Expressions 108

Bitwise Operators (<<, >>, , &, &hat;, ~) 114

Control Flow Statements, Continued 119

Jump Statements 130

C# Preprocessor Directives 136


Chapter 4: Methods and Parameters 147

Calling a Method 148

Declaring a Method 155

The using Directive 160

Returns and Parameters on Main() 164

Parameters 167

Recursion 174

Method Overloading 177

Basic Error Handling with Exceptions 180


Chapter 5: Classes 195

Defining and Instantiating a Class 199

Instance Fields 203

Instance Methods 205

Using the this Keyword 206

Access Modifiers 213

Properties 215

Constructors 229

Static 239

Extension Methods 249

Encapsulating the Data 250

Nested Classes 252

Partial Classes 254


Chapter 6: Inheritance 261

Derivation 262

Overriding the Base Class 272

Abstract Classes 284

Everything Ultimately Derives from System.Object 290

Verifying the Underlying Type with the is Operator 292

Conversion Using the as Operator 293


Chapter 7: Interfaces 295

Introducing Interfaces 296

Polymorphism through Interfaces 297

Interface Implementation 302

Casting between the Implementing Class and Its Interfaces 307

Interface Inheritance 308

Multiple Interface Inheritance 310

Extension Methods on Interfaces 311

Implementing Multiple Inheritance via Interfaces 313

Versioning 315

Interfaces Compared with Classes 317


Chapter 8: Value Types 321

Structs 322

Boxing 329

Enums 335


Chapter 9: Well-Formed Types 347

Overriding object Members 347

Operator Overloading 358

Referencing Other Assemblies 365

Defining Namespaces 370

XML Comments 373

Garbage Collection 377

Resource Cleanup 381


Chapter 10: Exception Handling 389

Multiple Exception Types 389

Catching Exceptions 391

General Catch Block 392

Guidelines for Exception Handling 395

Defining Custom Exceptions 397


Chapter 11: Generics 405

C# without Generics 406

Introducing Generic Types 411

Constraints 423

Generic Methods 436

Generic Internals 440


Chapter 12: Delegates and Lambda Expressions 445

Introducing Delegates 446

Anonymous Methods 456

System-Defined Delegates: Func<> 459

Lambda Expressions 460


Chapter 13: Events 479

Coding the Observer Pattern with Multicast Delegates 480

Events 495


Chapter 14: Collection Interfaces with Standard Query Operators 507

Anonymous Types and Implicit Local Variable Declaration 508

Collection Initializers 514

What Makes a Class a Collection: IEnumerable<T> 517

Standard Query Operators 523


Chapter 15: Query Expressions 555

Introducing Query Expressions 556

Query Expressions as Method Invocations 573


Chapter 16: Building Custom Collections 577

More Collection Interfaces 578

Primary Collection Classes 583

Providing an Index Operator 597

Returning Null or an Empty Collection 601

Iterators 601


Chapter 17: Reflection and Attributes 617

Reflection 618

Attributes 629


Chapter 18: Multithreading 657

Running and Controlling a Separate Thread 660

Passing Parameters to Threads 665

Thread Pooling 669

Unhandled Exceptions 670

Synchronization 672

Timers 691


Chapter 19: Multithreading Patterns 699

Asynchronous Results Pattern 700

Background Worker Pattern 714

Windows Forms 719


Chapter 20: Platform Interoperability and Unsafe Code 723

Platform Invoke 724

Pointers and Addresses 738


Chapter 21: The Common Language Infrastructure 749

Defining the Common Language Infrastructure (CLI) 750

CLI Implementations 751

C# Compilation to Machine Code 752

Runtime 755

Application Domains 760

Assemblies, Manifests, and Modules 761

Common Intermediate Language (CIL) 764

Common Type System (CTS) 764

Common Language Specification (CLS) 765

Base Class Library (BCL) 766

Metadata 766


Appendix A: Downloading and Installing the C# Compiler and the CLI Platform 771


Appendix B: Full Source Code Listings 775


Appendix C: C# 3.0 Topics 801


Index 807


Throughout the history of software engineering, the methodology used to write computer programs has undergone several paradigm shifts, each building on the foundation of the former by increasing code organization and decreasing complexity. This book takes you through these same paradigm shifts.

The beginning chapters take you through sequential programming structure in which statements are written in the order in which they are executed. The problem with this model is that complexity increases exponentially as the requirements increase. To reduce this complexity, code blocks are moved into methods, creating a structured programming model. This allows you to call the same code block from multiple locations within a program, without duplicating code. Even with this construct, however, programs quickly become unwieldy and require further abstraction. Object-oriented programming, discussed in Chapter 5, was the response. In subsequent chapters, you will learn about additional methodologies, such as interface-based programming, LINQ (and the transformation it makes to collection API), and eventually rudimentary forms of declarative programming (in Chapter 17) via attributes.

Essential C# 3.0 has three main functions.

  • It provides comprehensive coverage of the C# language, going beyond a tutorial and offering a foundation upon which you can begin effective software development projects.
  • For readers already familiar with C#, this book provides insight into some of the more complex programming paradigms and provides in-depth coverage of the features introduced in the latest version of the language, C# 3.0 and .NET 3.5.
  • Itserves as a timeless reference, even after you gain proficiency with the language.

The key to successfully learning C# is to start coding as soon as possible. Don't wait until you are an "expert" in theory; start writing software immediately. As a believer in iterative development, I hope this book enables even a novice programmer to begin writing basic C# code by the end of Chapter 2.

A number of topics are not covered in this book. You won't find coverage of topics such as ASP.NET, ADO.NET, smart client development, distributed programming, and so on. Although these topics are relevant to the .NET framework, to do them justice requires books of their own. Fortunately, Addison-Wesley's .NET Development Series provides a wealth of writing on these topics. Reading this book will prepare you to focus on and develop expertise in any of these areas. It focuses on C# and the types within the Base Class Library.

Target Audience for This Book

My challenge with this book was how to keep advanced developers awake while not abandoning beginners by using words like "assembly," "link," "chain," "thread," and "fusion," as if the topic was more appropriate for blacksmiths than for programmers. This book's primary audience is experienced developers looking to add another language to their quiver. However, I have carefully assembled this book to provide significant value to developers at all levels.

  • Beginners: If you are new to programming, this book serves as a resource to help transition you from an entry-level programmer to a C# developer, comfortable with any C# programming task that's thrown your way. This book not only teaches you syntax, but it also trains you in good programming practices that will serve you throughout your programming career.
  • Structured Programmers: Just as it's best to learn a foreign language through immersion, learning a computer language is most effective when you begin using it before you know all the intricacies. In this vein, this book begins with a tutorial that will be comfortable for those familiar with structured programming, and by the end of Chapter 4, developers in this category should feel at home writing basic control flow programs. However, the key to excellence for C# developers is not memorizing syntax. To transition from simple programs to enterprise development, the C# developer must think natively in terms of objects and their relationships. To this end, Chapter 5's Beginner Topics introduce classes and object-oriented development. The role of historically structured programming languages such as C, COBOL, and FORTRAN is still significant but shrinking, so it behooves software engineers to become familiar with object-oriented development. C# is an ideal language for making this transition because it was designed with object-oriented development as one of its core tenets.
  • Object-Based and Object-Oriented Developers: C++ and Java programmers, and many experienced Visual Basic programmers, fall into this category. Many of you are already completely comfortable with semicolons and curly braces. A brief glance at the code in Chapter 1 reveals that at its core, C# is similar to the C and C++ style languages that you already know.
  • C# Professionals: For those already versed in C#, this book provides a convenient reference for less frequently encountered syntax. Furthermore, it provides answers to language details and subtleties seldom addressed. Most importantly, it presents the guidelines and patterns for programming robust and maintainable code. This book also aids in the task of teaching C# to others.
  • With the emergence of C# 3.0, some of the most prominent enhancements are:

    • Implicitly typed variables (see Chapter 2)
    • Extension methods (see Chapter 5)
    • Partial methods (see Chapter 5)
    • Lambda expressions (see Chapter 12)
    • Expression trees (see Chapter 12)
    • Anonymous types (see Chapter 14)
    • Standard query operators (see Chapter 14)
    • Query expressions (see Chapter 15)
These topics are covered in detail for those not already familiar with them. Also pertinent to advanced C# development is the subject of pointers, in Chapter 21. Even experienced C# developers often do not understand this topic well.
Features of This Book

Essential C# 3.0 is a language book that adheres to the core C# Language 3.0 Specification. To help you understand the various C# constructs, it provides numerous examples demonstrating each feature. Accompanying each concept are guidelines and best practices, ensuring that code compiles, avoids likely pitfalls, and achieves maximum maintainability.

To improve readability, code is specially formatted and chapters are outlined using mind maps.

Code Samples

The code snippets in most of this text can run on any implementation of the Common Language Infrastructure (CLI), including the Mono, Rotor, and Microsoft .NET platforms. Platform- or vendor-specific libraries are seldom used, except when communicating important concepts relevant only to those platforms (appropriately handling the single-threaded user interface of Windows, for example). Any code that specifically requires C# 3.0 compliance is called out in the C# 3.0 Index at the end of the book.

In addition, the following special formatting assists readers:

  • Comments are shown in italics.
  • Keywords are shown in bold.
  • Highlighted code calls out specific code snippets that may have changed from an earlier listing, or demonstrates the concept described in the text. (Highlighting can appear on an entire line or on just a few characters within a line.)
  • Incomplete listings contain ellipses to denote irrelevant code that has been omitted.
  • Console output is the output from a particular listing that appears following the listing.
  • User input for the program appears in italics.

Although it might have been convenient to provide full code samples that you could copy into your own programs, doing so would detract you from learning a particular topic. Therefore, you need to modify the code samples before you can incorporate them into your programs. The core omission is error checking, such as exception handling. Also, code samples do not explicitly include using System statements. You need to assume the statement throughout all samples.

You can find sample code at and at

Mind Maps

Each chapter's introduction includes a mind map, which serves as an outline that provides at-a-glance reference to each chapter's content.

The theme of each chapter appears in the mind map's center. High-level topics spread out from the core. Mind maps allow you to absorb the flow from a high level to more detailed concepts easily, with less chance of encountering very specific knowledge that you might not be looking for.

Helpful Notes

Depending on your level of experience, special code blocks and tabs will help you navigate through the text.

  • Beginner Topics provide definitions or explanations targeted specifically toward entry-level programmers.
  • Advanced Topics enable experienced developers to focus on the material that is most relevant to them.
  • Callout notes highlight key principles in callout boxes so that readers easily recognize their significance.
  • Language Contrast sidebars identify key differences between C# and its predecessors to aid those familiar with other languages.
How This Book Is Organized

At a high level, software engineering is about managing complexity, and it is toward this end that I have organized Essential C# 3.0. Chapters 1-4 introduce structured programming, which enable you to start writing simple functioning code immediately. Chapters 5-9 present the object-oriented constructs of C#. Novice readers should focus on fully understanding this section before they proceed to the more advanced topics found in the remainder of this book. Chapters 11-13 introduce additional complexity-reducing constructs, handling common patterns needed by virtually all modern programs. This leads to dynamic programming with reflection and attributes, which is used extensively for threading and interoperability, the chapters that follow.

The book ends with a chapter on the Common Language Infrastructure, which describes C# within the context of the development platform in which it operates. This chapter appears at the end because it is not C# specific and it departs from the syntax and programming style in the rest of the book. However, this chapter is suitable for reading at any time, perhaps most appropriately immediately following Chapter 1.

Here is a description of each chapter. (In the following list, asterisks indicate entirely new chapters dedicated to C# 3.0 material. Bold chapter titles indicate chapters that contain C# 3.0 material.)

  • Chapter 1--Introducing C#: After presenting the C# HelloWorld program, this chapter proceeds to dissect it. This should familiarize readers with the look and feel of a C# program and provide details on how to compile and debug their own programs. It also touches on the context of a C# program's execution and its intermediate language.
  • Chapter 2--Data Types: Functioning programs manipulate data, and this chapter introduces the primitive data types of C#. This includes coverage of two type categories, value types and reference types, along with conversion between types and support for arrays.
  • Chapter 3--Operators and Control Flow: To take advantage of the iterative capabilities in a computer, you need to know how to include loops and conditional logic within your program. This chapter also covers the C# operators, data conversion, and preprocessor directives.
  • Chapter 4--Methods and Parameters: This chapter investigates the details of methods and their parameters. It includes passing by value, passing by reference, and returning data via a parameter. In C#, default parameters are not supported, and this chapter explains why and how to provide the same functionality.
  • Chapter 5--Classes: Given the basic building blocks of a class, this chapter combines these constructs together to form fully functional types. Classes form the core of object-oriented technology by defining the template for an object.
  • Chapter 6--Inheritance: Although inheritance is a programming fundamental to many developers, C# provides some unique constructs, such as the new modifier. This chapter discusses the details of the inheritance syntax, including overriding.
  • Chapter 7--Interfaces: This chapter demonstrates how interfaces are used to define the "versionable" interaction contract between classes. C# includes both explicit and implicit interface member implementation, enabling an additional encapsulation level not supported by most other languages.
  • Chapter 8--Value Types: Although not as prevalent as defining reference types, it is sometimes necessary to define value types that behave in a fashion similar to the primitive types built into C#. This chapter describes how to define structures, while exposing the idiosyncrasies they may introduce.
  • Chapter 9--Well-Formed Types: This chapter discusses more advanced type definition. It explains how to implement operators, such as + and casts, and describes how to encapsulate multiple classes into a single library. In addition, the chapter demonstrates defining namespaces and XML comments, and discusses how to design classes for garbage collection.
  • Chapter 10--Exception Handling: This chapter expands on the exception-handling introduction from Chapter 4 and describes how exceptions follow a hierarchy that enables creating custom exceptions. It also includes some best practices on exception handling.
  • Chapter 11--Generics: Generics is perhaps the core feature missing from C# 1.0. This chapter fully covers this new feature.
  • *Chapter 12--Delegates and Lambda Expressions: Delegates begin clearly distinguishing C# from its predecessors by defining patterns for handling events within code. This virtually eliminates the need for writing routines that poll. Lambda expressions are the key concept that make C# 3.0's LINQ possible. This chapter explains how lambda expressions build on the delegate construct by providing a more elegant and succinct syntax. This chapter forms the foundation for the new collection API discussed next.
  • Chapter 13--Events: Encapsulated delegates, known as events, are a core construct of the Common Language Runtime. Anonymous methods, another C# 2.0 feature, are also presented here.
  • *Chapter 14--Collection Interfaces with Standard Query Operators: The simple and yet elegantly powerful changes introduced in C# 3.0 begin to shine in this chapter as we take a look at the extension methods of the new Enumerable class. This class makes available an entirely new collection API known as the standard query operators and discussed in detail here.
  • *Chapter 15--Query Expressions: Using standard query operators alone results in some long statements that are hard to decipher. However, query expressions provides an alternate syntax that matches closely with SQL as described in this chapter.
  • *Chapter 16--Building Custom Collections: In building custom APIs that work against business objects are new entities, it is frequently necessary to create custom collections. This chapter details how to do this and in the process introduces contextual keywords that make custom collection building eaiser.
  • Chapter 17--Reflection and Attributes: Object-oriented programming formed the basis for a paradigm shift in program structure in the late 1980s. In a similar way, attributes facilitate declarative programming and embedded metadata, ushering in a new paradigm. This chapter looks at attributes and discusses how to retrieve them via reflection. It also covers file input and output via the serialization framework within the Base Class Library.
  • Chapter 18--Multithreading: Most modern programs require the use of threads to execute long-running tasks while ensuring active response to simultaneous events. As programs become more sophisticated, they must take additional precautions to protect data in these advanced environments. Programming multithreaded applications is complex. This chapter discusses how to work with threads and provides best practices to avoid the problems that plague multithreaded applications.
  • Chapter 19--Multithreading Patterns: Building on the last chapter, this one demonstrates some of the built-in threading pattern support that can simplify the explicit control of multithreaded code.
  • Chapter 20--Platform Interoperability and Unsafe Code: Given that C# is a relatively young language, far more code is written in other languages than in C#. To take advantage of this preexisting code, C# supports interoperability--the calling of unmanaged code--through P/Invoke. In addition, C# provides for the use of pointers and direct memory manipulation. Although code with pointers requires special privileges to run, it provides the power to interoperate fully with traditional C-based application programming interfaces.
  • Chapter 21--The Common Language Infrastructure: Fundamentally, C# is the syntax that was designed as the most effective programming language on top of the underlying Common Language Infrastructure. This chapter delves into how C# programs relate to the underlying runtime and its specifications.
  • Appendix A--Downloading and Installing the C# Compiler and the CLI Platform: This appendix provides instructions for setting up a C# compiler and the platform on which to run the code, Microsoft .NET or Mono.
  • Appendix B--Full Source Code Listings: In several cases, a full source code listing within a chapter would have been too long. To make these listings still available to the reader, this appendix includes full listing from Chapters 3, 11, 12, 14, and 17.
  • Appendix C--C# 3.0 Index: This index provides a quick reference for any C# 3.0 content. It is specifically designed to help C# 2.0 programmers to quickly get up to speed on the 3.0 features.

I hope you find this book to be a great resource in establishing your C# expertise and that you continue to reference it for the more obscure areas of C# and its inner workings.

Customer Reviews

Most Helpful Customer Reviews

See All Customer Reviews

Essential C# 3.0: For .NET Framework 3.5 (Microsoft .NET Development Series) 5 out of 5 based on 0 ratings. 1 reviews.
CaseyB More than 1 year ago
This book is wonderful to read whether you're at your computer or not! The concepts are so well explained and thoroughly exampled that it sinks in just upon reading. It is also laid out in such a way that you can come back to any idea extremely quickly for reference. One of my favorite thing about the book is that in each section he compares and contrasts the C# way of doing things with C++, Java and VB.