Essential C# 12.0, 8th Edition Mark Michaelis instant download
Essential C# 12.0, 8th Edition Mark Michaelis instant download
https://textbookfull.com/product/essential-c-12-0-8th-edition-
mark-michaelis/
https://textbookfull.com/product/essential-c-8-0-7th-edition-
mark-michaelis-kevin-bost-editor-eric-lippert-editor/
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/
https://textbookfull.com/product/pediatric-reference-
intervals-8th-edition-edward-c-c-wong-carlo-brugnara-joely-
straseski-mark-kellogg-khosrow-adeli/
https://textbookfull.com/product/macbook-for-dummies-8th-edition-
chambers-mark-l/
MacBook For Dummies 8th Edition Chambers Mark L
https://textbookfull.com/product/macbook-for-dummies-8th-edition-
chambers-mark-l-2/
https://textbookfull.com/product/macbook-for-dummies-8th-edition-
chambers-mark-l-3/
https://textbookfull.com/product/nolo-s-essential-guide-to-
divorce-8th-edition-emily-doskow/
https://textbookfull.com/product/rob-smiths-operative-pediatric-
surgery-8th-edition-mark-davenport/
https://textbookfull.com/product/structural-analysis-8th-edition-
solutions-manual-russell-c-hibbeler/
Essential
C# 12.0
Mark Michaelis
with Kevin Bost,
Technical Editor
Addison-Wesley
Hoboken, New Jersey
Cover image: Iam_Anuphone/Shutterstock
Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks
or trademarks of Microsoft Corporation in the U.S.A. and/or other countries/regions.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and the publisher was
aware of a trademark claim, the designations have been printed with initial capital letters or in all
capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed
or implied warranty of any kind and assume no responsibility for errors or omissions. No
liability is assumed for incidental or consequential damages in connection with or arising out of
the use of the information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to your
business, training goals, marketing focus, or branding interests), please contact our corporate
sales department at corpsales@pearsoned.com or (800) 382-3419.
For questions about sales outside the U.S., please contact intlcs@pearson.com.
Visit us on the Web: informit.com/aw
All rights reserved. This publication is protected by copyright, and permission must be obtained
from the publisher prior to any prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical, photocopying, recording, or
likewise. For information regarding permissions, request forms and the appropriate contacts
within the Pearson Education Global Rights & Permissions Department, please visit
www.pearson.com/permissions/.
ISBN-13: 978-0-13-821951-2
ISBN-10: 0-13-821951-6
$PrintCode
To my family: Elisabeth, Benjamin, Hanna, and Abigail. You
have sacrificed a husband and daddy for countless hours of
writing, frequently at times when he was needed most.
Thanks!
While we work hard to present unbiased content, we want to hear from you about
any concerns or needs with this Pearson product so that we can investigate and
address them.
Contents vii
Foreword xv
Preface xvii
Acknowledgments xxxi
About the Author xxxiii
1 Introducing C# 1
2 Data Types 49
3 More with Data Types 93
4 Operators and Control Flow 137
5 Parameters and Methods 217
6 Classes 293
7 Inheritance 385
8 Interfaces 443
9 Introducing Structs and Records 487
10 Well-Formed Types 547
11 Exception Handling 601
12 Generics 623
13 Delegates and Lambda Expressions 683
14 Events 727
15 Collection Interfaces with Standard Query Operators 755
16 LINQ with Query Expressions 809
17 Building Custom Collections 833
v
vi Contents at a Glance
Foreword xv
Preface xvii
Acknowledgments xxxi
About the Author xxxiii
1 Introducing C# 1
Hello, World 2
C# Syntax Fundamentals 12
Working with Variables 24
Console Input and Output 28
Managed Execution and the Common Language Infrastructure 38
Multiple .NET Frameworks 44
Summary 48
2 Data Types 49
Type Name Forms 50
Fundamental Numeric Types 52
More Fundamental Types 63
Conversions between Data Types 84
Summary 92
3 More with Data Types 93
Categories of Types 93
Declaring Types That Allow null 96
Implicitly Typed Local Variables 102
Tuples 103
Arrays 112
vii
viii Contents
Summary 134
4 Operators and Control Flow 137
Operators 137
Introducing Flow Control 156
Code Blocks ({}) 161
Code Blocks, Scopes, and Declaration Spaces 164
Boolean Expressions 166
Programming with null 173
Bitwise Operators (<<, >>, |, &, ^, ~) 181
Control Flow Statements, Continued 187
Jump Statements 200
C# Preprocessor Directives 206
Summary 215
5 Parameters and Methods 217
Calling a Method 218
Declaring a Method 225
Local Functions 232
Using Directives 233
Returns and Parameters on Main Method 242
Top-Level Statements 246
Advanced Method Parameters 247
Recursion 261
Method Overloading 264
Optional Parameters 267
Basic Error Handling with Exceptions 272
Summary 291
6 Classes 293
Declaring and Instantiating a Class 298
Instance Fields 302
Instance Methods 305
Using the this Keyword 306
Access Modifiers 314
Properties 316
Contents ix
Constructors 333
Non-Nullable Reference Type Properties with Constructors 346
Nullable Attributes 354
Deconstructors 357
Static Members 359
Extension Methods 370
Encapsulating the Data 372
Nested Classes 376
Partial Classes 379
Summary 384
7 Inheritance 385
Derivation 386
Overriding the Base Class 397
Abstract Classes 410
All Classes Derive from System.Object 417
Type Checking 419
Pattern Matching 423
Avoid Pattern Matching When Polymorphism Is Possible 438
Summary 440
8 Interfaces 443
Introducing Interfaces 444
Polymorphism through Interfaces 446
Interface Implementation 451
Converting between the Implementing Class and Its Interfaces 457
Interface Inheritance 458
Multiple Interface Inheritance 461
Extension Methods on Interfaces 461
Versioning 464
Extension Methods versus Default Interface Members 480
Interfaces Compared with Abstract Classes 482
Interfaces Compared with Attributes 484
Summary 484
9 Introducing Structs and Records 487
x Contents
Summary 1039
22 Thread Synchronization 1041
Why Synchronization? 1042
Timers 1073
Summary 1076
23 Platform Interoperability and Unsafe Code 1077
Platform Invoke 1078
Pointers and Addresses 1093
Executing Unsafe Code via a Delegate 1104
Summary 1105
24 The Common Language Infrastructure 1107
Defining the Common Language Infrastructure 1107
CLI Implementations 1109
.NET Standard 1113
Base Class Library 1113
C# Compilation to Machine Code 1114
Runtime 1116
Assemblies, Manifests, and Modules 1121
Common Intermediate Language 1124
Common Type System 1125
Common Language Specification 1125
Metadata 1126
.NET Native and Ahead of Time Compilation 1127
Summary 1128
Index 1131
Index of 8.0 Topics 1187
Index of 9.0 Topics 1190
Index of 10.0 Topics 1191
Index of 11.0 Topics 1192
Index of 12.0 Topics 1193
This page intentionally left blank
Foreword
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 Michaelis’s Essential C#
book has been a classic for years, but it was yet to see the light of day when I first got
to know Mark.
In 2005, when LINQ (Language Integrated Query) was disclosed, I had only just
joined Microsoft, and I got to tag along to the PDC conference for the big reveal.
Despite my almost total lack of contribution to the technology, I thoroughly enjoyed
the hype. The talks were overflowing, the printed leaflets were flying off the tables
like hotcakes: It was a big day for C# and .NET, and I was having a great time.
It was pretty quiet in the hands-on labs area, though, where people could try out
the technology preview themselves with nice scripted walkthroughs. That’s where I
ran into Mark. Needless to say, he wasn’t following the script. He was doing his own
experiments, combing through the docs, talking to other folks, busily pulling together
his own picture.
As a newcomer to the C# community, I may have met a lot of people for the first
time at that conference—people with whom I have since formed great relationships.
But to be honest, I don’t remember them—it’s all a blur. The only one I remember
is Mark. Here is why: When I asked him if he was liking the new stuff, he didn’t just
join the rave. He was totally level-headed: “I don’t know yet. I haven’t made up my
mind about it.” He wanted to absorb and understand the full package, and until then
he wasn’t going to let anyone tell him what to think.
So instead of the quick sugar rush of affirmation I might have expected, I got to
have a frank and wholesome conversation, the first of many over the years, about
details, consequences, and concerns with this new technology. And so it remains:
Mark is an incredibly valuable community member for us language designers to
have, because he is super smart, insists on understanding everything to the core, and
has phenomenal insight into how things affect real developers. But perhaps most of
all, he is forthright and never afraid to speak his mind. If something passes the Mark
Test, then we know we can start feeling pretty good about it!
xv
xvi Foreword
These are the same qualities that make Mark such a great writer. He goes right to
the essence and communicates with great integrity, no sugarcoating, and a keen eye
for practical value and real-world problems. Mark has a great gift of providing clarity
and elucidation, and no one will help you get C# 12.0 like he does.
Enjoy!
ㅤ
—Mads Torgersen
Principal Architect, Microsoft
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 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.
xvii
xviii Preface
These topics are covered in detail for those not already familiar with them. Also
pertinent to advanced C# development is the subject of pointers, covered in Chapter
23. Even experienced C# developers often do not understand this topic well.
Website
The interactive website for the book, available at https://essentialcsharp.com,
provides the online chapters, which allows full text search. Shortly after this writing,
I expect the website to provide interactive code editing and client-side compilation of
Preface xxi
many of the code listings. This will allow you to focus on the language rather than
getting distracted by installations or dotnet setup issues.
C# Coding Guidelines
One of the more significant enhancements included in Essential C# 12.0 is the 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. Visit https://intellitect.com/
Guidelines for a current list of all the guidelines.
xxii Preface
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 .NET
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# 8.0, 9.0, 10.0, 11.0, or 12.0 is called out in the C# version
indexes at the end of the book.
Here is a sample code listing.
Console.WriteLine("Hey you!");
• Highlighted code calls out specific code snippets that may have changed from
an earlier listing, or demonstrates the concept described in the text.
Console.WriteLine(text);
• Incomplete listings contain an ellipsis to denote irrelevant code that has been
omitted.
// ...
Output 1.7
Hey you!
Enter your first name: Inigo
Enter your last name: Montoya
• Console output is the output from a particular listing that appears following the
listing. 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
xxiv Preface
exception handling. Also, code samples do not explicitly include using System
statements. You need to assume the statement throughout all samples.
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.
Preface xxv
• 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 are 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 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 Enumerable class.
This class makes available a collection API known as the standard query
operators, which is 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.
xxviii Preface
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com