Preface

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 is organized in such a way as to take you through similar paradigm shifts.

The beginning chapters of Essential C# 6.0 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 may be 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, growing programs may quickly become unwieldy and require further abstraction. Object-oriented programming, discussed in Chapter 5, was a response intended to rectify this situation. In subsequent chapters of this book, you will learn about additional methodologies, such as interface-based programming, LINQ (and the transformation it makes to the collection API), and eventually rudimentary forms of declarative programming (in Chapter 17) 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#, it 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# 6.0 and .NET Framework 4.6.

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, Entity Framework, smart client development such as WPF, 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. Essential C# 6.0 focuses on C# and the types within the Base Class Library. Reading this book will prepare you to focus on and develop expertise in any of the areas covered by the rest of the series.

Target Audience for This Book

My challenge with this book was to keep advanced developers awake while not abandoning beginners by using terms such as assembly, link, chain, thread, and fusion, as though 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 arsenal—another arrow in their quiver, as it were. 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—one who is comfortable with any C# programming task that’s thrown your way. This book not only teaches you syntax, but also trains you in good programming practices that will serve you well throughout your programming career.

Structured programmers: Just as it’s best to learn a foreign language through immersion, so learning a computer language is most effective when you begin using that language before you know all of its 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 just memorizing syntax. Rather, 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 filled by 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++ styles of 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 that are 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, 4.0, 5.0, and now 6.0, some of the most prominent enhancements are as follows:

– Implicitly typed variables (see Chapter 2)

– Extension methods (see Chapter 5)

– Partial methods (see Chapter 5)

– Anonymous types (see Chapter 11)

– Generics (see Chapter 11)

– Lambda statements and expressions (see Chapter 12)

– Expression trees (see Chapter 12)

– Standard query operators (see Chapter 14)

– Query expressions (see Chapter 15)

– Dynamic programming (Chapter 17)

– Multithreaded programming with the Task Programming Library and async (Chapter 18)

– Parallel query processing with PLINQ (Chapter 18)

– Concurrent collections (Chapter 19)

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. Often, even experienced C# developers do not understand this topic well.

Features of This Book

Essential C# 6.0 is a language book that adheres to the core C# Language 6.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.

C# Coding Guidelines

One of the more significant features in Essential C# 6.0 is the inclusion of C# coding guidelines, as shown in the following example taken from Chapter 16:


Guidelines

DO ensure that equal objects have equal hash codes.

DO ensure that the hash code of an object never changes while it is in a hash table.

DO ensure that the hashing algorithm quickly produces a well-distributed hash.

DO ensure that the hashing algorithm is robust in any possible object state.


These guidelines are the key to differentiating a programmer who knows the syntax from an expert who is able to discern the most effective code to write based on the circumstances. Such an expert not only gets the code to compile, but does so while following best practices that minimize bugs and facilitate maintenance well into the future. The coding guidelines highlight some of the key principles that readers will want to be sure to incorporate into their development.

Code Samples

The code snippets in most of this text can run on any implementation of the Common Language Infrastructure (CLI), including the Mono, DNX Core, 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, 4.0, or 5.0 compliance is called out in the C# version, and separate indexes at the end of the book.

Here is a sample code listing.

LISTING 1.17: Swapping the Indexed Placeholders and Corresponding Variables


System.Console.WriteLine("Your full name is {1}, {0}",
  firstName, lastName);


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.4

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

User input for the program appears in boldface.

Although it might have been convenient to provide full code samples that you could copy into your own programs, doing so would detract from your 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 Intellitect.com/essentialcsharp and at informit.com/mstechseries. In addition, the code is available on Github—see http://itl.tc/EssentialCSharpSCC. Instructions for downloading the tools to compile the source code as well as the compilation instructions themselves are found in Appendix A.

You can also access the errata at http://Intellitect.com/essentialcsharp.

Mind Maps

Each chapter’s introduction includes a mind map, which serves as an outline that provides an at-a-glance reference to each chapter’s content. Here is an example (taken from Chapter 5).

Image

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 tabs will help you navigate through the text.

Beginner Topics provide definitions or explanations specifically targeted to entry-level programmers.

Advanced Topics enable experienced developers to focus on the material that is most relevant to them.

Callout notes highlight key principles 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.

Page-edge begin and end tabs denote material specific to C# versions; where that material continues over multiple pages, just the version number appears in the tab.

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# 6.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 in 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 this list, chapter numbers shown in bold italics indicate the presence of C# 3.0–5.0 material).

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. Chapter 1 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. Default parameter support was added in C# 4.0, and this chapter explains how to use this support.

Chapter 5Classes: Given the basic building blocks of a class, this chapter combines these constructs 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 it is more common to define 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 9Well-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 the process of defining namespaces and the use of 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 supports the creation of 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 2.0 feature. In addition, C# 4.0 added support for covariance and contravariance—something covered in the context of generics in this chapter.

Chapter 12Delegates and Lambda Expressions: Delegates begin clearly distinguishing C# from its predecessors by defining patterns for handling events within code. This practice virtually eliminates the need for writing routines that poll. Lambda expressions are the key concept that make C# 3.0’s LINQ possible. Chapter 12 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 13Events: 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 14Collection Interfaces with Standard Query Operators: The simple, 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, which is discussed in detail here.

Chapter 15LINQ with Query Expressions: Using standard query operators alone results in some long statements that can be challenging to decipher. However, query expressions provide an alternative syntax that matches closely with SQL, as described in this chapter.

Chapter 16Building Custom Collections: In building custom APIs that work against business objects, it is sometimes necessary to create custom collections. This chapter details how to do this, and in the process introduces contextual keywords that make custom collection building easier.

Chapter 17Reflection, Attributes, and Dynamic Programming: 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. In C# 4.0, a new keyword, dynamic, was added to the language. It removed all type checking until runtime, a significant expansion of what can be done with C#.

Chapter 18Multithreading: Most modern programs require the use of threads to execute long-running tasks while ensuring they provide an active response to simultaneous events. As programs become more sophisticated, they must take additional precautions to protect data in these dynamic 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 19Thread Synchronization: Building on the preceding chapter, Chapter 19 demonstrates some of the built-in threading pattern support that can simplify the explicit control of multithreaded code.

Chapter 20Platform 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 21The 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 BTic-Tac-Toe Source Code Listing: This appendix provides a full listing of the Tic-Tac-Toe program referred to in Chapters 3 and 4.

C# 3.0, 4.0, 5.0, and 6.0 Indexes—These indexes provide a quick reference for the features added in C# 3.0 through 6.0. They are specifically designed to help programmers quickly update their language skills to a more recent version.

Appendix C, Interfacing with Multithreading Patterns Prior to the TPL and C# 6.0, and Appendix D, Timers Prior to the Async/Await Pattern of C# 6.0, can be found on the book’s website, http://www.informit.com/title/9780134141046. Teaching resources that accompany this book will be made available to qualified instructors through Pearson’s Instructor Resource Center.

I hope that 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.

—Mark Michaelis
Blog: http://IntelliTect.com/mark
Twitter: @Intellitect, @MarkMichaelis

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

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