Table of Contents....10
Acknowledgments....20
Introduction....22
The Great Game of Programming....22
Book Features....23
Speedruns....23
Challenges and Boss Battles....24
Knowledge Checks....25
Experience Points and Levels....25
Narratives and the Plot....25
Side Quests....26
Glossary....26
The Website....26
Discord....26
I Want Your Feedback....27
An Overview....27
Part 1: The Basics....28
1 The C# Programming Language....30
What is C#?....30
What is .NET?....31
2 Getting an IDE....32
A Comparison of IDEs....32
Visual Studio....33
Visual Studio Code....33
Visual Studio for Mac....33
JetBrains Rider....33
Other IDEs....33
Online Editors....34
No IDE....34
Installing Visual Studio....34
3 Hello World: Your First Program....36
Creating a New Project....36
A Brief Tour of Visual Studio....38
Compiling and Running Your Program....39
Syntax and Structure....40
Strings and Literals....41
Identifiers....41
Hierarchical Organization....41
Classes and Methods....42
Namespaces....42
The Base Class Library....43
Program and Main....43
Statements....44
Whitespace....44
Beyond Hello World....45
Multiple Statements....45
Expressions....45
Variables....46
Reading Text from the Console....47
Compiler Errors, Debuggers, and Configurations....48
Compiler Errors and Warnings....48
Debugging....48
Build Configurations....48
4 Comments....50
How to Make Good Comments....51
5 Variables....53
What is a Variable?....53
Creating and Using Variables in C#....54
Integers....55
Reading from a Variable Does Not Change It....56
Clever Variable Tricks....56
Variable Names....57
6 The C# Type System....59
Representing Data in Binary....59
Integer Types....60
Declaring and Using Variables with Integer Types....61
The Digit Separator....62
Choosing Between the Integer Types....62
Binary and Hexadecimal Literals....63
Text: Characters and Strings....63
Floating-Point Types....64
Scientific Notation....66
The bool Type....66
Type Inference....67
The Convert Class and the Parse Methods....68
Parse Methods....69
7 Math....71
Operations and Operators....71
Addition, Subtraction, Multiplication, and Division....72
Compound Expressions and Order of Operations....73
Special Number Values....75
Integer Division vs. Floating-Point Division....75
Division by Zero....76
More Operators....76
Unary + and - Operators....76
The Remainder Operator....76
Updating Variables....77
Increment and Decrement Operators....78
Prefix and Postfix Increment and Decrement Operators....78
Working with Different Types and Casting....79
Overflow and Roundoff Error....81
The Math and MathF Classes....82
π and e....82
Powers and Square Roots....82
Absolute Value....82
Trigonometric Functions....83
Min, Max, and Clamp....83
More....83
The MathF Class....83
8 Console 2.0....84
The Console Class....84
The Write Method....84
The ReadKey Method....85
Changing Colors....85
The Clear Method....85
Changing the Window Title....86
The Beep Method....86
Sharpening Your String Skills....86
Escape Sequences....86
String Interpolation....87
Alignment....87
Formatting....88
9 Decision Making....90
The if Statement....90
Block Statements....91
Blocks, Variables, and Scope....92
The else Statement....94
else if Statements....94
Relational Operators: ==, !=, <, >, <=, >=....95
Using bool in Decision Making....96
Logical Operators....97
Nesting if Statements....98
The Conditional Operator....98
10 Switches....100
Switch Statements....101
Multiple Cases for the Same Arm....102
Switch Expressions....102
Switches as a Basis for Pattern Matching....103
11 Looping....105
The while Loop....105
The do/while Loop....107
Variables Declared in Block Statements and Loops....107
The for Loop....107
break Out of Loops and continue to the Next Pass....108
Nesting Loops....109
12 Arrays....111
Creating Arrays....112
Getting and Setting Values in Arrays....112
Default Values....113
Crossing Array Bounds....113
Indexing from the End....114
Ranges....114
Other Ways to Create Arrays....114
Some Examples with Arrays....115
The foreach Loop....116
Multi-Dimensional Arrays....116
13 Methods....118
Defining a Method....118
Local Functions....119
Calling a Method....120
Methods Get Their Own Variables....121
Passing Data to a Method....122
Multiple Parameters....123
Copied Values in Method Calls....123
Returning a Value from a Method....124
Returning Early....125
Multiple Return Values?....125
Method Overloading....125
Simple Methods with Expressions....126
XML Documentation Comments....127
The Basics of Recursion....128
14 Memory Management....130
Memory and Memory Management....131
The Stack....131
Parameters....134
Return Values....136
Fixed-Size Stack Frames....136
The Heap....136
The Heap as a Graph of Objects....138
Value Types and Reference Types....139
Value Semantics and Reference Semantics....142
Cleaning Up Heap Memory....143
Automatic Memory Management....143
Part 2: Object-Oriented Programming....148
15 Object-Oriented Concepts....150
Object-Oriented Concepts....150
16 Enumerations....153
Enumeration Basics....154
Defining an Enumeration....154
Using an Enumeration....155
Revisiting ConsoleColor....156
Underlying Types....157
17 Tuples....158
The Basics of Tuples....159
Tuple Element Names....160
Tuples and Methods....160
More Tuple Examples....161
Deconstructing Tuples....162
Ignoring Elements with Discards....163
Tuples and Equality....163
18 Classes....165
Defining a New Class....166
Instances of Classes....168
Constructors....169
Default Constructors and Default Field Values....170
Constructors with Parameters....170
Multiple Constructors....171
Initializing Fields Inline....171
Name Hiding and the this Keyword....172
Calling Other Constructors with this....174
Leaving Off the Class Name....174
Object-Oriented Design....174
19 Information Hiding....176
The public and private Accessibility Modifiers....177
The Default Accessibility Level is private....180
When to Use private and public....180
Accessibility Levels as Guidelines, Not Laws....180
Abstraction....180
Type Accessibility Levels and the internal Modifier....181
20 Properties....184
The Basics of Properties....184
Auto-Implemented Properties....187
Immutable Fields and Properties....188
Object Initializer Syntax and Init Properties....189
Anonymous Types....190
21 Static....191
Static Members....191
Static Fields....191
Global State....192
Static Properties....192
Static Methods....193
Static Constructors....193
Static Classes....194
22 Null References....195
Null or Not?....196
Disabling Nullable Type Warnings....196
Checking for Null....197
Null-Conditional Operators: ?. and ?[]....197
The Null Coalescing Operator: ??....198
The Null-Forgiving Operator: !....198
23 Object-Oriented Design....199
Requirements....200
Designing the Software....201
Noun Extraction....201
UML....202
CRC Cards....202
Evaluating a Design....205
Creating Code....206
How to Collaborate....208
Creating New Objects....208
Constructor Parameters....208
Method Parameters....208
Asking Another Object....209
Supplying the Reference via Property or Method....209
Static Members....209
Choices, Choices....210
Baby Steps....210
24 The Catacombs of the Class....211
The Five Prototypes....211
Object-Oriented Design....214
Tic-Tac-Toe....216
25 Inheritance....218
Inheritance and the object Class....219
Choosing Base Classes....221
Constructors....222
Casting and Checking for Types....224
The protected Access Modifier....225
Sealed Classes....225
26 Polymorphism....227
Abstract Methods and Classes....229
New Methods....230
27 Interfaces....232
Defining Interfaces....233
Implementing Interfaces....234
Interfaces and Base Classes....235
Explicit Interface Implementations....235
Default Interface Methods....236
Supporting Default Interface Methods....237
Should I Use Default Interface Methods?....238
28 Structs....239
Memory and Constructors....240
Classes vs. Structs....241
Choosing to Make a Class or a Struct....242
Rules to Follow When Making Structs....244
Built-In Type Aliases....245
Boxing and Unboxing....246
29 Records....248
Records....248
String Representation....249
Value Semantics....249
Deconstruction....249
with Statements....249
Advanced Scenarios....250
Additional Members....250
Replacing Synthesized Members....250
Non-Positional Records....251
Struct- and Class-Based Records....251
Inheritance....252
When to Use a Record....252
30 Generics....253
The Motivation for Generics....253
Defining a Generic Type....256
Multiple Generic Type Parameters....257
Inheritance and Generic Types....257
Generic Methods....258
Generic Type Constraints....258
Multiple Constraints....260
Constraints on Methods....260
The default Operator....260
31 The Fountain of Objects....262
The Main Challenge....263
Expansions....265
32 Some Useful Types....268
The Random Class....269
The DateTime Struct....270
The TimeSpan Struct....271
The Guid Struct....272
The List Class....273
Creating List Instances....273
Indexing....273
Adding and Removing Items from List....274
foreach Loops....274
Other Useful Things....275
The IEnumerable Interface....276
The Dictionary Class....277
Types Besides string....278
Dictionary Keys Should Not Change....278
The Nullable Struct....279
ValueTuple Structs....279
The StringBuilder Class....280
Part 3: Advanced Topics....282
33 Managing Larger Programs....284
Using Multiple Files....284
Namespaces and using Directives....285
Advanced using Directive Features....287
Global using Directives....287
Static using Directives....287
Name Conflicts and Aliases....287
Putting Types into Namespaces....288
Namespace Naming Conventions....289
Traditional Entry Points....289
34 Methods Revisited....292
Optional Arguments....292
Named Arguments....293
Variable Number of Parameters....293
Combinations....294
Passing by Reference....294
Output Parameters....296
There’s More!....297
Deconstructors....297
Extension Methods....298
35 Error Handling and Exceptions....301
Handling Exceptions....302
Handling Specific Exception Types....303
Using the Exception Object....304
Throwing Exceptions....304
The finally Block....305
Exception Guidelines....306
What to Handle....306
Only Handle What You Can Fix....306
Use the Right Exception Type....306
Avoid Pokémon Exception Handling....307
Avoid Eating Exceptions....307
Avoid Throwing Exceptions When Possible....307
Come Back with Your Shield or On It....308
Advanced Exception Handling....309
Stack Traces....309
Rethrowing Exceptions....309
Inner Exceptions....310
Exception Filters....310
36 Delegates....312
Delegate Basics....312
The Action, Func, and Predicate Delegates....315
MulticastDelegate and Delegate Chaining....316
37 Events....317
C# Events....317
Events with Parameters....319
Null Events....320
Event Leaks....321
EventHandler and Friends....321
Custom Event Accessors....322
38 Lambda Expressions....324
Lambda Expression Basics....324
The Origin of the Name Lambda....325
Multiple and Zero Parameters....326
When Type Inference Fails....326
Discards....326
Lambda Statements....326
Closures....327
39 Files....329
The File Class....329
String Manipulation....331
Other String Parsing Methods....332
File System Manipulation....333
The Directory Class....333
The Path Class....334
There’s More!....334
Other Ways to Access Files....334
Streams....334
Find a Library....336
40 Pattern Matching....337
The Constant Pattern and the Discard Pattern....338
The Monster Scoring Problem....338
The Type and Declaration Patterns....339
Case Guards....340
The Property Pattern....340
Nested Patterns....341
Relational Patterns....341
The and, or, and not Patterns....342
The Positional Pattern....342
Deconstructors and the Positional Pattern....343
The var Pattern....343
Parenthesized Patterns....343
Patterns with Switch Statements and the is Keyword....343
Switch Statements....343
The is Keyword....344
Summary....344
41 Operator Overloading....346
Operator Overloading....347
Defining an Operator Overload....347
When to Overload Operators....348
Indexers....348
Index Initializer Syntax....349
Custom Conversions....350
The Pitfalls of Custom Conversions and Some Alternatives....351
42 Query Expressions....354
Queries and IEnumerable....355
Sample Classes....355
Query Expression Basics....355
Filtering....356
Ordering....357
Method Call Syntax....357
Unique Methods....358
Advanced Queries....359
Multiple from Clauses....359
Joining Multiple Collections Together....359
The let Clause....360
Continuation Clauses....360
Grouping....360
Group Joins....361
Deferred Execution....361
LINQ to SQL....362
43 Threads....364
The Basics of Threads....364
Using Threads....365
Sharing Data with a Thread....366
Sleeping....367
Thread Safety....368
Locks....369
44 Asynchronous Programming....372
A Sample Problem....373
Threads and Callbacks....373
Using Tasks....374
Task and Task Basics....374
The async and await Keywords....376
Who Runs My Code?....377
Some Additional Details....379
Exceptions....379
Cancellation....379
Awaitables....379
Limitations....380
More Information....380
45 Dynamic Objects....382
Dynamic Type Checking....383
Dynamic Objects....383
Emulating Dynamic Objects with Dictionaries....384
Using ExpandoObject....384
Extending DynamicObject....385
When to Use Dynamic Object Variations....386
46 Unsafe Code....388
Unsafe Contexts....389
Pointer Types....389
Fixed Statements....390
Stack Allocations....391
Fixed-Size Arrays....391
The sizeof Operator....391
The nint and nuint Types....392
Calling Native Code with Platform Invocation Services....392
47 Other Language Features....394
Iterators and the yield Keyword....395
Async Enumerables....396
Constants....396
Attributes....397
Attributes on Everything....398
Attributes are Classes....398
Reflection....399
The nameof Operator....400
Nested Types....400
Even More Accessibility Modifiers....401
Bit Manipulation....401
Bitshift Operators....402
Bitwise Logical Operators....403
Flags Enumerations....404
using Statements and the IDisposable Interface....405
Preprocessor Directives....406
#warning and #error....406
#region and #endregion....406
Working with Conditional Compilation Symbols....407
Command-Line Arguments....408
Partial Classes....408
Partial Methods....409
The Notorious goto Keyword....409
Generic Covariance and Contravariance....410
Checked and Unchecked Contexts....412
Volatile Fields....413
48 Beyond a Single Project....414
Outgrowing a Single Project....414
NuGet Packages....417
49 Compiling in Depth....420
Hardware....420
Assembly....422
Programming Languages....422
Instruction Set Architectures....423
Virtual Machines and Runtimes....423
50 .NET....425
The History of .NET....425
The Components of .NET....426
Common Infrastructure....426
Common Intermediate Language....426
The Common Language Runtime....426
The .NET Software Development Kit....427
Base Class Library....427
App Models....428
Web App Models....428
Mobile App Models....428
Desktop App Models....428
Game Development....429
51 Publishing....430
Build Configurations....430
Publish Profiles....431
.pubxml Files....434
Publishing with a Profile....434
After Publishing....434
Part 4: The Endgame....436
52 The Final Battle....438
Overview....439
Core Challenges....440
Expansions....444
53 Into Lands Uncharted....450
Keep Learning....450
Other Frameworks and Libraries....450
Other Topics....451
Make Software....451
Do the Side Quests....451
Where Do I Go to Get Help?....451
Parting Words....452
Part 5: Bonus Levels....454
A Visual Studio Overview....456
Windows....456
The Code Window....457
Code Navigation....458
IntelliSense....458
Quick Actions....459
The Solution Explorer....460
The Properties Window....461
The Error List....461
Other Windows....461
The Options Dialog....462
B Compiler Errors....463
Code Problems: Errors, Warnings, and Messages....463
How to Resolve Compiler Errors....464
Compile Often....464
Use a Quick Action....464
Make Sure You Understand the Key Parts of the Error Message....464
Backup or Undo....464
Be Cautious with Internet Code....465
Be Careful Transcribing Code....465
Fix the Errors that Make Sense....465
Look Around....465
Take a Break....465
Read the Documentation....465
Ask for Help....466
Common Compiler Errors....466
“The name ‘x’ doesn’t exist in the current context”....466
“) expected”, “} expected”, “] expected”, and “; expected”....466
Cannot convert type ‘x’ to ‘y’....467
“not all code paths return a value”....467
“The type or namespace name ‘x’ could not be found”....467
C Debugging Your Code....468
Some Broken Sample Code....468
Print Debugging....469
Using a Debugger....469
Breakpoints....470
Stepping Through Code....471
Edit and Continue and Hot Reload....472
Breakpoint Conditions and Actions....472
Glossary....473
Index....489
Like an entertaining video game, programming is often a challenging but always rewarding experience. This book shakes off the dusty, dull and dry typical programming book, replacing it with something more exciting and interesting: a little humor, a relaxed tone and examples with dragons and asteroids instead of bank accounts and employees.And since you learn to program by doing, not just reading, this book contains more than 100 practical programming tasks. You will be creating software, not just reading about it. By completing tasks, you will earn experience points, increase your level and become a real C# programmer!This book covers the C# language from scratch. This does not mean that you have been programming for many years, but you also do not give up on interesting and powerful language features.The journey begins with preparing for C# programming.Then we'll learn the basic mechanics of C#: operators, expressions, variables, if statements, loops, and methods.Next, we will delve into a powerful and central feature of C#: object-oriented programming, which is an important tool needed to create larger programs.Next, we'll look at the advanced features of C# that make the language unique, elegant, and powerful.With this book as a companion, you will soon set out to save the world (or conquer it) with your own C# programs!The fifth edition has been updated for C#10, .NET 6 and Visual Studio 2022.