Praise for Essential C 2.0

Praise for Essential C# 2.0

"Essential C# 2.0 pulls off a very difficult task. The early chapters are comprehensible by beginning developers, while the later chapters pull no punches and provide the experienced developer with the detailed information they need to make the most of C# 2.0. Starting with the first chapter, Mark has successfully interwoven tidbits of information useful to even the most advanced developer while keeping the book approachable."

Chris Kinsman, chief architect, Vertafore, Microsoft Regional Director

"How refreshing! This book deals with C# thoroughly, rather than skimming over the whole .NET framework. It is valuable to newcomers and professionals alike."

Jon Skeet, C# MVP

"Essential C# 2.0 is a one-stop shop for an experienced programmer looking to ramp up on one of the hottest languages around today. Mark delivers an intelligent and detailed tour of C#, providing newcomers to the language with a solid foundation of skill on which to build their next generation of applications."

Stephen Toub, technical editor, MSDN Magazine

"This book provides complete, up-to-date coverage of all the programming constructs in C#. Masterfully organized, it allows beginning programmers to get on board and leads more experienced programmers into the world of structured programming. Because of its unwavering focus on the essential programming constructs of C#such as generics, delegates, and much morethis book is indispensable. For programmers who want to solve their day-to-day programming issues using the latest features this modern programming language has to offer, this book is indispensable."

Narendra Poflee, IT integration specialist, Itron Inc.

"Essential C# 2.0 is an ideal book for all programmers interested in C#. If you are a beginner, you will quickly learn the basics of C# programming and become familiar with the concepts. The flow of the text is easy to follow and does a great job of not repeating concepts that have already been covered. For the experienced programmer, this book has priceless nuggets embedded within its pages, making it a great read for programmers who are already familiar with C#. This will be a book that I will keep next to my computer for years to come."

Michael Stokesbary, software engineer, Itron Inc.


For those in the industry who have watched the C programming language develop to embrace new concepts such as object programming (C++), ubiquity across platforms (Java), and highly structured models that form the basis of C#, it is clear that the language is well positioned to hold its own as a dominant development language.

This book has everything a developer needs to know to get up and running with the language. Many concise code samples, the use of mind maps to provide context, and the interesting way Mark contrasts C# with other languages make Essential C# 2.0 stand out in a sea of C# books.

I have known Mark for a while now. His extensive involvement in the development of C# principles, together with his prior experience as an author of books on C++, COM+, and C#, uniquely qualify him to write the book that I believe will be a seminal reference for C#.

Further, Mark's teaching experience allows him to combine the world of technical skill with that of practical, intuitive tutorial. It begins with principles of object programming in C#, as it is a reference to verify advanced multithreading techniques in a complex system. The reader, novice or expert, will enjoy his casual style and method of eloquently communicating challenging topics.

This reference and tutorial should be on the shelf next to your workstation and carried in your backpack. Pick it up and read it! Im confident that whether you are new or experienced with the language, you will learn something in this book that will induce an "aha!" moment!

Prashant Sridharan

Microsoft Corporation

March 2006


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, which creates 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. From this emerges object-oriented programming, which Chapter 5 discusses. In subsequent chapters, you continue to learn about additional methodologies, such as interface-based programming, and eventually rudimentary forms of declarative programming (in Chapter 14) via attributes.

This book 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# 2.0.

  • It serves 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 Microsoft .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, the 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# 2.0, some of the most prominent enhancements are:

    - Partial classes (see Chapter 5)

    - Global namespace qualifiers (see Chapter 9)

    - Different access modifiers on property getters and setters (see Chapter 5

    - Anonymous methods (see Chapter 13)

    - Generics (see Chapter 11)

    - Iterator topics (see Chapter 12)

    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 17. Even experienced C# developers often do not understand this topic well.

Features of This Book

Essential C# 2.0 is a language book that adheres to the core C# Language 2.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# 2.0 compliance is called out in Appendix C: C# 2.0 Topics.

Here is a sample code listing.

Listing 1.17. Commenting Your Code

The formatting is as follows.

  • Comments are shown in italics.

    /* Display a greeting to the console    using composite formatting. */

  • Keywords are shown in bold.

    static void Main()

  • Highlighted code calls out specific code snippets that may have changed from an earlier listing, or demonstrates the concept described in the text.

    System.Console.Write /* No new line */ (

  • Highlighting can appear on an entire line or on just a few characters within a line.

    System.Console.WriteLine(       "Your full name is {0} {1}." ,

  • Incomplete listings contain an ellipsis to denote irrelevant code that has been omitted.

    // ...

  • Console output is the output from a particular listing that appears following the listing.

Output 1.1.

>HeyYou.exe Hey you! Enter your first name: Inigo Enter your last name: Montoya

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. Here is an example (taken from Chapter 12).

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 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 notes 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# 2.0. Chapters 14 introduce structured programming, which enable you to start writing simple functioning code immediately. Chapters 59 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 1113 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.

  • Chapter 1Introducing 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 2Data 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 3Operators 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 4Methods 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 5Classes: 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 6Inheritance: 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 7Interfaces: 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 8Value 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 9WellFormed Types: This chapter discusses more advanced type definition. It explains how to implement operators, such as + and cast, 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 10Exception 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 11Generics: Generics is perhaps the core feature missing from C# 1.0. This chapter fully covers this new feature.

  • Chapter 12Collections: Given generics, all the collection classes in .NET 1.1 can be replaced with their generic equivalents. This chapter reviews the collection classes, along with the interfaces that define their common behavior. With minimal impact on the underlying runtime, C# 2.0 provides syntax for easier collection creation with iterators. Iterators provide a clean syntax for specifying how to loop through data within a class.

  • Chapter 13Delegates and Events: 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. 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 14Reflection 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 15Multithreading: 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 16Multithreading 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 17Platform 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 interoperabilitythe calling of unmanaged codethrough 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 18The 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 ADownloading 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 BComplete 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 the full listing from Chapters 3, 11, 12, 14, and 17.

  • Appendix CC# 2.0 Topics: This appendix provides a quick reference to any C# 2.0 content. It is specifically designed to help C# 1.0 programmers quickly get up to speed on the 2.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.


Figure 2.1 Value Types Contain the Data Directly 51

Figure 2.2 Reference Types Point to the Heap 52

Figure 3.1 Corresponding Placeholder Values 108

Figure 3.2 Calculating the Value of an Unsigned Byte 108

Figure 3.3 Calculating the Value of a Signed Byte 109

Figure 3.4 12 and 7 Represented in Binary 110

Figure 3.5 Collapsed Region in Microsoft Visual Studio .NET 137

Figure 4.1 Exception Handling Program Flow 176

Figure 5.1 Class Hierarchy 188

Figure 6.1 Refactoring into a Base Class 238

Figure 6.2 Working around Multiple Inheritance Using Aggregation 247

Figure 7.1 Working around Single Inheritances with Aggregation and Interfaces 291

Figure 8.1 Value Types Contain the Data Directly 298

Figure 8.2 Reference Types Point to the Heap 299

Figure 9.1 Identity 327

Figure 9.2 XML Comments as Tips in Visual Studio IDE 350

Figure 12.1 List<> and ArrayList Class Diagrams 422

Figure 12.2 Dictionary and Hashtable Class Diagrams 425

Figure 12.3 SortedList<> and SortedDictionary<> Class Diagrams 431

Figure 12.4 Stack<T> and Stack Class Diagrams 432

Figure 12.5 Queue<T> and Queue Class Diagrams 433

Figure 12.6 LinkedList<T> and LinkedListNode<T> Class Diagram 434

Figure 12.7 Generic Collection Interface Hierarchy 435

Figure 12.8 IEnumerator<T> and IEnumerator Interfaces


Figure 12.9 Sequence Diagram with yield return454

Figure 13.1 Delegate Types Object Model 469

Figure 13.2 Delegate Invocation Sequence Diagram 491

Figure 13.3 Multicast Delegates Chained Together 492

Figure 13.4 Delegate Invocation with Exception Sequence Diagram 494

Figure 14.1 MemberInfo Derived Classes 518

Figure 14.2 BinaryFormatter Does Not Encrypt Data 541

Figure 16.1 Delegate Parameter Distribution to BeginInvoke() and EndInvoke() 600

Figure 17.1 Pointers Contain the Address of the Data 632

Figure 18.1 Compiling C# to Machine Code 646

Figure 18.2 Assemblies with the Modules and Files They Reference 654


Table 1.1 C# Keywords 7

Table 1.2 C# Comment Types 23

Table 2.1 Integer Types 30

Table 2.2 Floating-Point Types 32

Table 2.3 decimal Type 32

Table 2.4 Escape Characters 40

Table 2.5 string Static Methods 44

Table 2.6 string Instance Methods 45

Table 2.7 Common Array Coding Errors 74

Table 3.1 Control Flow Statements 93

Table 3.2 Relational and Equality Operators 103

Table 3.3 Conditional Values for the XOR Operator 106

Table 3.4 Preprocessor Directives 131

Table 3.5 Operator Order of Precedence 137

Table 4.1 Common Namespaces 143

Table 4.2 Common Exception Types 179

Table 6.1 Why the New Modifier? 256

Table 6.2 Members of System.Object269

Table 7.1 Comparing Abstract Classes and Interfaces 294

Table 8.1 Boxing Code in CIL 306

Table 9.1 Accessibility Modifiers 345

Table 14.1 Deserialization of a New Version Throws an Exception 543

Table 15.1 Sample Pseudocode Execution 566

Table 15.2 Interlock's Synchronization-Related Methods 574

Table 15.3 Overview of the Various Timer Characteristics 585

Table 18.1 Primary C# Compilers 643

Table 18.2 Common C#-Related Acronyms 660

Table C.1 Topics by Page Number 693

Table C.2 Topics by Title 695

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: