Cover....1
Copyright....4
Table of Contents....7
Preface....19
Who This Book Is For....19
Conventions Used in This Book....19
Using Code Examples....20
O’Reilly Online Learning....21
How to Contact Us....21
Acknowledgments....22
Chapter 1. Introducing C#....23
Why C#?....24
Managed Code and the CLR....26
C# Prefers Generality to Specialization....28
C# Standards and Implementations....29
Many .NETs....29
Release Cycles and Long Term Support....31
Targeting Multiple .NET Runtimes....32
Visual Studio, Visual Studio Code, and JetBrains Rider....34
Anatomy of a Simple Program....37
Writing a Unit Test....42
Namespaces....47
Classes....52
Unit Tests....54
Summary....55
Chapter 2. Basic Coding in C#....57
Local Variables....58
Scope....64
Variable Name Ambiguity....65
Local Variable Instances....67
Statements and Expressions....68
Statements....68
Expressions....69
Comments and Whitespace....76
Preprocessing Directives....78
Compilation Symbols....78
#error and #warning....80
#line....80
#pragma....81
#nullable....82
#region and #endregion....82
Fundamental Data Types....83
Numeric Types....83
Booleans....95
Strings and Characters....95
Tuples....108
Tuple Deconstruction....110
Dynamic....112
Object....113
Operators....113
Flow Control....119
Boolean Decisions with if Statements....120
Multiple Choice with switch Statements....122
Loops: while and do....124
C-Style for Loops....125
Collection Iteration with foreach Loops....127
Patterns....128
Combining and Negating Patterns....135
Relational Patterns....136
Getting More Specific with when....137
Patterns in Expressions....137
Summary....140
Chapter 3. Types....141
Classes....141
Initialization Inputs....144
Static Members....146
Static Classes....148
Records....150
References and Nulls....156
Banishing Null with Non-Nullable References....160
Structs....168
When to Write a Value Type....173
Guaranteeing Immutability....177
Record Structs....178
Class, Structs, Records, or Tuples?....179
Members....181
Accessibility....181
Fields....181
Constructors....184
Deconstructors....197
Methods....199
Properties....216
Operators....229
Events....232
Nested Types....232
Interfaces....234
Default Interface Implementation....236
Static Virtual Members....238
Enums....240
Other Types....243
Anonymous Types....244
Partial Types and Methods....247
Summary....248
Chapter 4. Generics....249
Generic Types....250
Constraints....252
Type Constraints....253
Reference Type Constraints....256
Value Type Constraints....258
Value Types All the Way Down with Unmanaged Constraints....259
Not Null Constraints....259
Other Special Type Constraints....259
Multiple Constraints....260
Zero-Like Values....260
Generic Methods....262
Type Inference....263
Generic Math....264
Generic Math Interfaces....267
Numeric Category Interfaces....267
Operator Interfaces....272
Function Interfaces....273
Parsing and Formatting....274
Generics and Tuples....275
Summary....276
Chapter 5. Collections....277
Arrays....277
Array Initialization....281
Searching and Sorting....284
Multidimensional Arrays....288
Copying and Resizing....292
List....293
List and Sequence Interfaces....297
Implementing Lists and Sequences....304
Implementing IEnumerable with Iterators....304
Collection....308
ReadOnlyCollection....309
Addressing Elements with Index and Range Syntax....310
System.Index....311
System.Range....313
Supporting Index and Range in Your Own Types....316
Dictionaries....318
Sorted Dictionaries....321
Sets....323
Queues and Stacks....324
Linked Lists....325
Concurrent Collections....326
Immutable Collections....327
Frozen Collections....330
Summary....331
Chapter 6. Inheritance....333
Inheritance and Conversions....335
Interface Inheritance....338
Generics....339
Covariance and Contravariance....341
System.Object....347
The Ubiquitous Methods of System.Object....347
Accessibility and Inheritance....348
Virtual Methods....350
Abstract Methods....352
Inheritance and Library Versioning....354
Static Virtual Methods....360
Default Constraints....361
Sealed Methods and Classes....364
Accessing Base Members....366
Inheritance and Construction....367
Primary Constructors....369
Mandatory Properties....371
Field Initialization....372
Record Types....374
Records, Inheritance, and the with Keyword....376
Special Base Types....377
Summary....378
Chapter 7. Object Lifetime....379
Garbage Collection....380
Determining Reachability....382
Accidentally Defeating the Garbage Collector....384
Weak References....387
Reclaiming Memory....390
Lightening the Load with Inline Arrays....396
Garbage Collector Modes....398
Temporarily Suspending Garbage Collections....401
Accidentally Defeating Compaction....402
Forcing Garbage Collections....405
Destructors and Finalization....406
IDisposable....409
Optional Disposal....417
Boxing....418
Boxing Nullable....423
Summary....424
Chapter 8. Exceptions....425
Exception Sources....427
Exceptions from APIs....428
Failures Detected by the Runtime....431
Handling Exceptions....432
Exception Objects....433
Multiple catch Blocks....435
Exception Filters....436
Nested try Blocks....437
finally Blocks....439
Throwing Exceptions....441
Rethrowing Exceptions....443
Failing Fast....446
Exception Types....446
Custom Exceptions....448
Unhandled Exceptions....450
Summary....452
Chapter 9. Delegates, Lambdas, and Events....453
Delegate Types....454
Creating a Delegate....456
Multicast Delegates....460
Invoking a Delegate....461
Common Delegate Types....463
Type Compatibility....465
Behind the Syntax....467
Anonymous Functions....469
Lambdas and Default Arguments....473
Captured Variables....476
Lambdas and Expression Trees....484
Events....486
Standard Event Delegate Pattern....488
Custom Add and Remove Methods....489
Events and the Garbage Collector....491
Events Versus Delegates....493
Delegates Versus Interfaces....494
Summary....495
Chapter 10. LINQ....497
Query Expressions....498
How Query Expressions Expand....501
Deferred Evaluation....503
LINQ, Generics, and IQueryable....506
Standard LINQ Operators....508
Filtering....510
Select....513
SelectMany....516
Ordering....519
Containment Tests....522
Specific Items and Subranges....523
Whole-Sequence, Order-Preserving Operations....528
Aggregation....529
Grouping....534
Conversion....539
Sequence Generation....544
Other LINQ Implementations....544
Entity Framework Core....544
Parallel LINQ (PLINQ)....545
LINQ to XML....545
IAsyncEnumerable....546
Reactive Extensions....546
Summary....546
Chapter 11. Rx: Reactive Extensions....547
Fundamental Interfaces....549
IObserver....551
IObservable....552
Publishing and Subscribing with Delegates....558
Creating an Observable Source with Delegates....558
Subscribing to an Observable Source with Delegates....562
Sequence Builders....563
Empty....563
Never....563
Return....564
Throw....564
Range....564
Repeat....565
Generate....565
LINQ Queries....566
Grouping Operators....568
Join Operators....570
SelectMany Operator....573
Aggregation and Other Single-Value Operators....574
Concat Operator....575
Rx Query Operators....575
Merge....576
Windowing Operators....577
The Scan Operator....584
The Amb Operator....586
DistinctUntilChanged....587
Schedulers....587
Specifying Schedulers....588
Built-in Schedulers....590
Subjects....591
Subject....592
BehaviorSubject....592
ReplaySubject....593
AsyncSubject....593
Adaptation....593
IEnumerable and IAsyncEnumerable....594
.NET Events....596
Asynchronous APIs....597
Timed Sequences....599
Timed Sources....599
Timed Operators....600
Timed Windowing Operators....602
Reaqtor—Rx as a Service....603
Summary....604
Chapter 12. Assemblies and Deployment....605
Anatomy of an Assembly....606
.NET Metadata....607
Resources....607
Multifile Assemblies....607
Other PE Features....608
Type Identity....609
Deployment....613
Framework-Dependent....613
Self-Contained....615
Trimming....616
Ahead-of-Time (AOT) Compilation....617
Loading Assemblies....620
Assembly Resolution....621
Explicit Loading....623
Isolation and Plug-ins with AssemblyLoadContext....625
Assembly Names....627
Strong Names....627
Version....630
Version Numbers and Assembly Loading....632
Culture....633
Protection....637
Target Frameworks and .NET Standard....638
Summary....640
Chapter 13. Reflection....641
Reflection Types....643
Assembly....644
Module....648
MemberInfo....648
Type and TypeInfo....651
Generic Types....655
MethodBase, ConstructorInfo, and MethodInfo....657
ParameterInfo....658
FieldInfo....659
PropertyInfo....659
EventInfo....660
Reflection Contexts....660
Summary....662
Chapter 14. Attributes....663
Applying Attributes....663
Attribute Targets....666
Compiler-Handled Attributes....669
CLR-Handled Attributes....677
Debugging Attributes....680
Build-Time Attributes....681
Defining and Consuming Attributes....683
Attribute Types....684
Retrieving Attributes....685
Metadata-Only Load....687
Generic Attribute Types....688
Summary....689
Chapter 15. Files and Streams....691
The Stream Class....692
Position and Seeking....694
Flushing....695
Copying....696
Length....696
Disposal....697
Asynchronous Operation....697
Concrete Stream Types....698
One Type, Many Behaviors....700
Text-Oriented Types....701
TextReader and TextWriter....702
Concrete Reader and Writer Types....704
Encoding....706
Files and Directories....709
FileStream Class....710
File Class....712
Directory Class....714
Path Class....714
Serialization....715
BinaryReader, BinaryWriter, and BinaryPrimitives....716
CLR Serialization....717
JSON....718
Summary....728
Chapter 16. Multithreading....729
Threads....729
Threads, Variables, and Shared State....731
Thread-Local Storage....734
The Thread Class....736
The Thread Pool....738
Thread Affinity and SynchronizationContext....740
ExecutionContext....743
Synchronization....744
Monitors and the lock Keyword....745
Other Synchronization Primitives....752
Interlocked....752
Lazy Initialization....754
Other Class Library Concurrency Support....756
Tasks....758
The Task and Task Classes....758
Continuations....764
Schedulers....766
Error Handling....768
Custom Threadless Tasks....768
Parent/Child Relationships....770
Composite Tasks....770
Other Asynchronous Patterns....771
Cancellation....772
Parallelism....773
The Parallel Class....773
Parallel LINQ....775
TPL Dataflow....775
Summary....775
Chapter 17. Asynchronous Language Features....777
Asynchronous Keywords: async and await....778
Execution and Synchronization Contexts....782
Multiple Operations and Loops....784
Returning a Task....791
Applying async to Nested Methods....793
The await Pattern....793
Error Handling....798
Validating Arguments....800
Singular and Multiple Exceptions....802
Concurrent Operations and Missed Exceptions....803
Summary....804
Chapter 18. Memory Efficiency....807
(Don’t) Copy That....808
Representing Sequential Elements with Span....812
Utility Methods....816
Collection Expressions and Spans....817
Pattern Matching....817
Stack Only....818
Using ref with Fields....819
Representing Sequential Elements with Memory....823
ReadOnlySequence....824
Processing Data Streams with Pipelines....824
Processing JSON in ASP.NET Core....827
Summary....832
Index....835
About the Author....875
Colophon....875
C# is undeniably one of the most versatile programming languages available to engineers today. With this comprehensive guide, you'll learn just how powerful the combination of C# and .NET can be. Author Ian Griffiths guides you through C# 12.0 and .NET 8 fundamentals and techniques for building cloud, web, and desktop applications.
Designed for experienced programmers, this book provides many code examples to help you work with the nuts and bolts of C#, such as generics, LINQ, and asynchronous programming features. You'll get up to speed on .NET 8 and the latest C# 11.0 and 12.0 additions, including generic math, new polymorphism options, enhanced pattern matching, and new features designed to improve productivity.C# has now existed for around two decades. It has grown steadily in both power and size, but Microsoft has always kept the essential characteristics intact. Each new capability is designed to integrate cleanly with the rest, enhancing the language without turning it into an incoherent bag of miscellaneous features. Even though C# continues to be a fairly straightforward language at its heart, there is a great deal more to say about it now than in its first incarnation. Because there is so much ground to cover, this book expects a certain level of technical ability from its readers.
The C# programming language (pronounced “see sharp”) is used for many kinds of applications, including websites, cloud-based systems, artificial intelligence, IoT devices, desktop applications, embedded controllers, mobile apps, games, and command-line utilities. C#, along with the supporting runtime, libraries, and tools known collectively as .NET, has been center stage for Windows developers for over 20 years. Today, .NET is cross-platform and open source, enabling applications and services written in C# to run on operating systems including Android, iOS, macOS, and Linux, as well as on Windows.
C# 11.0 and 12.0 have gained performance-oriented features including generic math, and improved control over memory handling for performance-sensitive low-level code. Every new .NET release has improved execution speed, but there have also been significant reductions in startup times, memory footprint, and binary size. This, along with improved support for containerization, enhances .NET’s fit for modern cloud development. There have also been significant improvements for cross-platform client-side development, thanks to Blazor and .NET MAUI (Multi-platform App UI). .NET has supported ARM and WebAssembly (WASM) for many years, but continuous recent improvements for those targets are important for cloud, mobile, and web development.
I have written this book for experienced developers—I’ve been programming for years, and I set out to make this the book I would want to read if that experience had been in other languages, and I were learning C# today. Whereas earlier editions explained some basic concepts such as classes, polymorphism, and collections, I am assuming that readers will already know what these are. The early chapters still describe how C# presents these common ideas, but the focus is on the details specific to C#, rather than the broad concepts.