Effective techniques and experienced insights to maximize your C# 6 and 7 programming skills
Key Features
Written by C# legend and top StackOverflow contributor Jon Skeet Unlock the new features of C# 6 and 7 Insights on the future of the C# language Master asynchronous functions, interpolated strings, tuples, and more
Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.
”An excellent overview of C# with helpful and realistic examples that make learning the newest features of C# easy.” —Meredith Godar
About The Book C# is the foundation of .NET development. New features added in C# 6 and 7 make it easier to take on big data applications, cloud-centric web development, and cross-platform software using .NET Core. Packed with deep insight from C# guru Jon Skeet, this book takes you deep into concepts and features other C# books ignore.
C# in Depth, Fourth Edition is an authoritative and engaging guide that reveals the full potential of the language, including the new features of C# 6 and 7. It combines deep dives into the C# language with practical techniques for enterprise development, web applications, and systems programming. As you absorb the wisdom and techniques in this book, you’ll write better code, and become an exceptional troubleshooter and problem solver.
What You Will Learn
Comprehensive guidance on the new features of C# 6 and 7 Important legacies and greatest hits of C# 2–5 Expression-bodied members Extended pass-by-reference functionality Writing asynchronous C# code String interpolation Composition with tuples Decomposition and pattern matching
This Book Is Written For For intermediate C# developers.
About The Author Jon Skeet is a senior software engineer at Google. He studied mathematics and computer science at Cambridge, is a recognized authority in Java and C#, and maintains the position of top contributor to Stack Overflow.
Table of Contents
1. Survival of the sharpest 2. C# 2 3. C# 3: LINQ and everything that comes with it 4. C# 4: Improving interoperability 5. Writing asynchronous code 6. Async implementation 7. C# 5 bonus features 8. Super-sleek properties and expression-bodied members 9. Stringy features 10. A smörgåsbord of features for concise code 11. Composition using tuples 12. Deconstruction and pattern matching 13. Improving efficiency with more pass by reference 14. Concise code in C# 7 15. C# 8 and beyond
Manning publishes the best quality IT books in the industry.
Manning is an independent publisher, providing computer books for software developers, engineers, architects, system administrators, and managers. Our books also cover topics for young programmers, students, and occasionally children.
summary
Manning is an independent publisher of computer books and video courses for software developers, engineers, architects, system administrators, managers and all who are professionally involved with the computer business. We also publish for students and young programmers, including occasionally for children. We are an entirely virtual organization based on Shelter Island, New York, with many staff working from far-flung places like Manila and Zagreb.
company character
“Independent” means we are not owned by a large corporate entity and are free to make decisions without bureaucratic overhead. That has allowed us to innovate and be flexible and to quickly adjust what we do as we go. We were the first by several years to sell our books as unprotected PDFs, something that later became commonplace. We were the first to start selling books before they were finished, in the Manning Early Access Program. This gave our readers access to our content as soon as it was readable, and this too has become common in the industry. And it means we are thinking every day about new ways to satisfy our customers, some of which we hope you will be pleased to discover in the not-too-distant future.
how we improve
We published our first book in 1993 and have been learning from our successes, and even more from our mistakes, ever since. Every new book teaches us something that helps us improve:
How to choose the topics we publish on
How to find the right authors for each book
How to help authors write the best books they can
How to ensure the content is valuable and easy to learn
How to let readers know about our content
book series
We publish standalone titles as well as the following book series:
Hello!
In Action
In Practice
In Depth
In a Month of Lunches
availability
Readers can access our books through the Manning Early Access Program, O’Reilly Learning (formerly Safari Books Online), and iBooks. Print copies, wherever they are bought, come with free electronic versions in PDF, ePub and Kindle formats. With your print copy in hand, register it on the Manning site and you can download the digital versions from your account.
At this time, our eBooks are available only from Manning.com and Apple’s iBookstore.
When you have questions about C# 9.0 or .NET 5, this best-selling guide has the answers you need. C# is a language of unusual flexibility and breadth, but with its continual growth there’s so much more to learn. In the tradition of O’Reilly’s Nutshell guides, this thoroughly updated edition is simply the best one-volume reference to the C# language available today.
Organized around concepts and use cases, C# 9.0 in a Nutshell provides intermediate and advanced programmers with a concise map of C# and .NET that also plumbs significant depths.
Get up to speed on C#, from syntax and variables to advanced topics such as pointers, records, closures, and patterns
Dig deep into LINQ with three chapters dedicated to the topic
Explore concurrency and asynchrony, advanced threading, and parallel programming
Work with .NET features, including regular expressions, networking, spans, reflection, and cryptography
This quick C# 8 guide is a condensed code and syntax reference to the C# programming language, updated with the latest features of C# 8 for .NET and Windows 10. This book presents the essential C# 8 syntax in a well-organized format that can be used as a handy reference. Specifically, it covers nullable reference types, async streams, ranges and indices, default implementations of interface members, recursive patterns, switch expressions, target-typed new-expressions, platform dependencies and more. In the C# 8 Quick Syntax Reference, you will find a concise reference to the C# language syntax: short, simple, and focused code examples; a well laid out table of contents; and a comprehensive index allowing easy review. You won’t find any technical jargon, bloated samples, drawn-out history lessons, or witty stories. What you will find is a language reference that is to the point and highly accessible. The book is packed with useful information and is a must-have for any C# programmer.
What You Will Learn
Discover what’s new in C# 8 and .NET for Windows 10 programming
Employ nullable reference types
Explore the advanced async streams now available in C# 8
Work with ranges and indices
Apply recursive patterns to your applications
Use switch expressions
Who This Book Is For
Those with some experience in programming, looking for a quick, handy reference. Some C# or .NET recommended but not necessary.
When you have questions about C# 9.0 or .NET 5, this best-selling guide has the answers you need. C# is a language of unusual flexibility and breadth, but with its continual growth there’s so much more to learn. In the tradition of O’Reilly’s Nutshell guides, this thoroughly updated edition is simply the best one-volume reference to the C# language available today.
Organized around concepts and use cases, C# 9.0 in a Nutshell provides intermediate and advanced programmers with a concise map of C# and .NET that also plumbs significant depths.
Get up to speed on C#, from syntax and variables to advanced topics such as pointers, records, closures, and patterns
Dig deep into LINQ with three chapters dedicated to the topic
Explore concurrency and asynchrony, advanced threading, and parallel programming
Work with .NET features, including regular expressions, networking, spans, reflection, and cryptography
Joseph Albahari is author of C# 8.0 in a Nutshell, C# 8.0 Pocket Reference, and LINQ Pocket Reference (all from O’Reilly). He also wrote LINQPad, the popular code scratchpad and LINQ querying utility.
The Comprehensive, Expert Guide to C# 8.0 for Programmers at All Levels “Welcome to one of the most venerable and trusted franchises you could dream of in the world of C# books—and probably far beyond! . . . Mark is super smart, insists on understanding everything to the core, and has phenomenal insight into how things affect real developers. . . . He goes right to the essence and communicates with great integrity—no sugarcoating—and has a keen eye for practical value and real-world problems.” — From the Foreword by Mads Torgersen, C# Lead Designer, Microsoft Essential C# 8.0 is a well-organized, no-fluff guide to C# 8.0 for programmers at all levels of experience. This edition retains all the valuable content of prior editions and adds discussions of null reference types, indices and ranges, enhanced pattern matching, asynchronous stream, and more.
World-class C# expert Mark Michaelis presents a comprehensive tutorial and reference for the entire language, providing an accelerated learning opportunity to achieve expert C# programming skills. He includes key C# 8.0 enhancements, succinct examples to illustrate central constructs, and updated coding guidelines for minimizing bugs and writing code that’s easier to evolve. To help you quickly fi nd what you need, there are version-specific indexes of C# 6.0, 7.0, and 8.0 topics and visual icons that identify when each language innovation was introduced.
Use structured programming constructs to write functioning code immediately
Learn both the complexities and solutions to nullable reference types
Thoroughly master C# object constructs, including classes, inheritance, and interfaces
Reduce code redundancy with generics, delegates, lambda expressions, and events
Take full advantage of collections, including the new standard query operator collection API
Make the most of reflection, attributes, and the declarative programming paradigm
Improve multithreading with the task-based async pattern and C# 8.0 asynchronous streams
Enhance performance through the parallel processing of data and multithreading tasks
Program complex types with enhanced pattern matching syntax
Interoperate with unmanaged code written in other languages, including C-based APIs
Explore the relationship between C# programs and the underlying CLI runtime
Biography:
Mark Michaelis (itl.tc/Mark) is the founder of IntelliTect and serves as the Chief Technical Architect and Trainer. A premier authority in Microsoft development technologies with recognized coding expertise and proven training methods, IntelliTect’s CEO delivers customized strategic technology consulting to CIOs, technology executives, and industry leaders. Recognized by Microsoft as a Regional Director since 2007 and distinguished Microsoft MVP for C# and Visual Studio Team System since 1996, this CEO has honed his engineering skills by serving on several Microsoft software design review teams, including C#, Azure and Visual Studio Team System ALM.
“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 executed in the order in which they are written. 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, introduced in Chapter 6, was the response. In subsequent chapters, 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 18) 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# 7.0 and .NET Framework 4.7/.NET Core 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.
Many topics are not covered in this book. You won’t find coverage of topics such as ASP.NET, ADO.NET, Xamarin, smart client development, distributed programming, and so on. Although these topics are relevant to .NET, to do them justice requires books of their own. Fortunately, Addison-Wesley’s Microsoft Windows Development Series provides a wealth of writing on these topics. Essential C# 7.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 words 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 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 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 5, 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 6’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++, Java, Python, TypeScript, Visual Basic, and Java 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 like other 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 that are seldom addressed. Most important, 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 through 7.0, some of the most prominent enhancements are
– String interpolation (see Chapter 2)
– Implicitly typed variables (see Chapter 3)
– Tuples (see Chapter 3)
– Pattern matching (see Chapter 4)
– Extension methods (see Chapter 6)
– Partial methods (see Chapter 6)
– Anonymous types (see Chapter 12)
– Generics (see Chapter 12)
– Lambda statements and expressions (see Chapter 13)
– Expression trees (see Chapter 13)
– Standard query operators (see Chapter 15)
– Query expressions (see Chapter 16)
– Dynamic programming (Chapter 18)
– Multithreaded programming with the Task Programming Library and async (Chapter 19)
– Parallel query processing with PLINQ (Chapter 19)
– Concurrent collections (Chapter 20)
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# 7.0 is a language book that adheres to the core C# Language 7.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 enhancements included in Essential C# 7.0 is C# coding guidelines, as shown in the following example taken from Chapter 17:
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 can 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 enable 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 most implementations of the Common Language Infrastructure (CLI), but the focus is on the Microsoft .NET Framework and the .NET Core implementation. Platform- or vendor-specific libraries are seldom used except when communicating important concepts relevant only to those platforms (e.g., appropriately handling the single-threaded user interface of Windows). Any code that specifically relates to C# 5.0, 6.0, or 7.0 is called out in the C# version indexes at the end of the book.
Here is a sample code listing.
Begin 2.0
LISTING 1.19: Commenting Your Code
Click here to view code image
class Comment Samples { static void Main() { string firstName; //Variable for storing the first name string lastName; //Variable for storing the last name System.Console.WriteLine(“Hey you!”); System.Console.Write /* No new line / ( “Enter your first name: “); firstName = System.Console.ReadLine(); System.Console.Write / No new line / ( “Enter your last name: “); lastName = System.Console.ReadLine(); / Display a greeting to the console using composite formatting. */ System.Console.WriteLine(“Your full name is {0} {1}.”, firstName, lastName); // This is the end // of the program listing } }
The formatting is as follows.
Comments are shown in italics.
Click here to view code image
/* 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.
Click here to view code image
System.Console.WriteLine(valerie); miracleMax = “It would take a miracle.”; System.Console.WriteLine(miracleMax);
Highlighting can appear on an entire line or on just a few characters within a line.
Click here to view code image
System.Console.WriteLine( “Your full name is {0} {1}.”, firstName, lastName);
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. User input for the program appears in boldface.
OUTPUT 1.7
Click here to view code image
Hey you! Enter your first name: Inigo Enter your last name: Montoya Your full name is Inigo Montoya.
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 https://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 6).
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 features 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# 7.0. Chapters 1–5 introduce structured programming, which enable you to start writing simple functioning code immediately. Chapters 6–10 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 12–14 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 indicate the presence of C# 6.0–7.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#.
Chapter 3—More with Data Types: This chapter includes coverage of two type categories, value types and reference types. From there, it delves into the nullable modifier and a C# 7.0-introduced feature, tuples. It concludes with an in-depth look at a primitive array structure.
Chapter 4—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 5—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 an out parameter. In C# 4.0, default parameter support was added, and this chapter explains how to use default parameters.
Chapter 6—Classes: 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 7—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 8—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 9—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 10—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 11—Exception Handling: This chapter expands on the exception-handling introduction from Chapter 5 and describes how exceptions follow a hierarchy that enables creating custom exceptions. It also includes some best practices on exception handling.
Chapter 12—Generics: 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 13—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 14—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 15—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 16—LINQ with Query Expressions: Using standard query operators alone results in some long statements that are hard to decipher. However, query expressions provide an alternative syntax that matches closely with SQL, as described in this chapter.
Chapter 17—Building 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 18—Reflection, 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. This removed all type checking until runtime, a significant expansion of what can be done with C#.
Chapter 19—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 20—Thread Synchronization: Building on the preceding chapter, this one demonstrates some of the built-in threading pattern support that can simplify the explicit control of multithreaded code.
Chapter 21—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 22—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.
Indexes of C# 5.0, 6.0, and 7.0 Topics: These indexes provide quick references for the features added in C# 4.0 through 7.0. They are specifically designed to help programmers quickly update their language skills to a more recent version.” (EC8MM)