The C# Player's Guide

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

The book in your hands is a different kind of programming book. Like an entertaining video game, programming is an often challenging but always rewarding experience. This book shakes off the dusty, dull, dryness of the typical programming book, replacing it with something more exciting and flavorful: a bit of humor, a casual tone, and examples involving dragons and asteroids instead of bank accounts and employees. And since you learn to program by doing instead of just reading, this book contains over 100 hands-on programming challenges. You will be building software instead of just reading about it. By completing the challenges, you’ll earn experience points, level up, and become a True C# Programmer! This book covers the C# language from the ground up. It doesn’t assume you’ve been programming for years, but it also doesn’t hold back on exciting, powerful language features. * The journey begins by getting you set up to program in C#. * We will then explore the basic mechanics of C#: statements, expressions, variables, if statements, loops, and methods. * Next, we dive deep into a powerful and central feature of C#: object-oriented programming, which is an essential tool needed to build larger programs. * We then look at the advanced C# features that make the language unique, elegant, and powerful. With this book as your companion, you will soon be off to save the world (or take it over) with your own C# programs! The 5th Edition is updated for C# 10, .NET 6, and Visual Studio 2022.

Author(s): RB Whitaker
Edition: 5
Publisher: Starbound Software
Year: 2022

Language: English
Pages: 475

Table of Contents
Acknowledgments
Introduction
The Great Game of Programming
Book Features
Speedruns
Challenges and Boss Battles
Knowledge Checks
Experience Points and Levels
Narratives and the Plot
Side Quests
Glossary
The Website
Discord
I Want Your Feedback
An Overview
Part 1: The Basics
1 The C# Programming Language
What is C#?
What is .NET?
2 Getting an IDE
A Comparison of IDEs
Visual Studio
Visual Studio Code
Visual Studio for Mac
JetBrains Rider
Other IDEs
Online Editors
No IDE
Installing Visual Studio
3 Hello World: Your First Program
Creating a New Project
A Brief Tour of Visual Studio
Compiling and Running Your Program
Syntax and Structure
Strings and Literals
Identifiers
Hierarchical Organization
Classes and Methods
Namespaces
The Base Class Library
Program and Main
Statements
Whitespace
Beyond Hello World
Multiple Statements
Expressions
Variables
Reading Text from the Console
Compiler Errors, Debuggers, and Configurations
Compiler Errors and Warnings
Debugging
Build Configurations
4 Comments
How to Make Good Comments
5 Variables
What is a Variable?
Creating and Using Variables in C#
Integers
Reading from a Variable Does Not Change It
Clever Variable Tricks
Variable Names
6 The C# Type System
Representing Data in Binary
Integer Types
Declaring and Using Variables with Integer Types
The Digit Separator
Choosing Between the Integer Types
Binary and Hexadecimal Literals
Text: Characters and Strings
Floating-Point Types
Scientific Notation
The bool Type
Type Inference
The Convert Class and the Parse Methods
Parse Methods
7 Math
Operations and Operators
Addition, Subtraction, Multiplication, and Division
Compound Expressions and Order of Operations
Special Number Values
Integer Division vs. Floating-Point Division
Division by Zero
More Operators
Unary + and - Operators
The Remainder Operator
Updating Variables
Increment and Decrement Operators
Prefix and Postfix Increment and Decrement Operators
Working with Different Types and Casting
Overflow and Roundoff Error
The Math and MathF Classes
π and e
Powers and Square Roots
Absolute Value
Trigonometric Functions
Min, Max, and Clamp
More
The MathF Class
8 Console 2.0
The Console Class
The Write Method
The ReadKey Method
Changing Colors
The Clear Method
Changing the Window Title
The Beep Method
Sharpening Your String Skills
Escape Sequences
String Interpolation
Alignment
Formatting
9 Decision Making
The if Statement
Block Statements
Blocks, Variables, and Scope
The else Statement
else if Statements
Relational Operators: ==, !=, <, >, <=, >=
Using bool in Decision Making
Logical Operators
Nesting if Statements
The Conditional Operator
10 Switches
Switch Statements
Multiple Cases for the Same Arm
Switch Expressions
Switches as a Basis for Pattern Matching
11 Looping
The while Loop
The do/while Loop
Variables Declared in Block Statements and Loops
The for Loop
break Out of Loops and continue to the Next Pass
Nesting Loops
12 Arrays
Creating Arrays
Getting and Setting Values in Arrays
Default Values
Crossing Array Bounds
Indexing from the End
Ranges
Other Ways to Create Arrays
Some Examples with Arrays
The foreach Loop
Multi-Dimensional Arrays
13 Methods
Defining a Method
Local Functions
Calling a Method
Methods Get Their Own Variables
Passing Data to a Method
Multiple Parameters
Copied Values in Method Calls
Returning a Value from a Method
Returning Early
Multiple Return Values?
Method Overloading
Simple Methods with Expressions
XML Documentation Comments
The Basics of Recursion
14 Memory Management
Memory and Memory Management
The Stack
Parameters
Return Values
Fixed-Size Stack Frames
The Heap
The Heap as a Graph of Objects
Value Types and Reference Types
Value Semantics and Reference Semantics
Cleaning Up Heap Memory
Automatic Memory Management
Part 2: Object-Oriented Programming
15 Object-Oriented Concepts
Object-Oriented Concepts
16 Enumerations
Enumeration Basics
Defining an Enumeration
Using an Enumeration
Revisiting ConsoleColor
Underlying Types
17 Tuples
The Basics of Tuples
Tuple Element Names
Tuples and Methods
More Tuple Examples
Deconstructing Tuples
Ignoring Elements with Discards
Tuples and Equality
18 Classes
Defining a New Class
Instances of Classes
Constructors
Default Constructors and Default Field Values
Constructors with Parameters
Multiple Constructors
Initializing Fields Inline
Name Hiding and the this Keyword
Calling Other Constructors with this
Leaving Off the Class Name
Object-Oriented Design
19 Information Hiding
The public and private Accessibility Modifiers
The Default Accessibility Level is private
When to Use private and public
Accessibility Levels as Guidelines, Not Laws
Abstraction
Type Accessibility Levels and the internal Modifier
20 Properties
The Basics of Properties
Auto-Implemented Properties
Immutable Fields and Properties
Object Initializer Syntax and Init Properties
Anonymous Types
21 Static
Static Members
Static Fields
Global State
Static Properties
Static Methods
Static Constructors
Static Classes
22 Null References
Null or Not?
Disabling Nullable Type Warnings
Checking for Null
Null-Conditional Operators: ?. and ?[]
The Null Coalescing Operator: ??
The Null-Forgiving Operator: !
23 Object-Oriented Design
Requirements
Designing the Software
Noun Extraction
UML
CRC Cards
Evaluating a Design
Creating Code
How to Collaborate
Creating New Objects
Constructor Parameters
Method Parameters
Asking Another Object
Supplying the Reference via Property or Method
Static Members
Choices, Choices
Baby Steps
24 The Catacombs of the Class
The Five Prototypes
Object-Oriented Design
Tic-Tac-Toe
25 Inheritance
Inheritance and the object Class
Choosing Base Classes
Constructors
Casting and Checking for Types
The protected Access Modifier
Sealed Classes
26 Polymorphism
Abstract Methods and Classes
New Methods
27 Interfaces
Defining Interfaces
Implementing Interfaces
Interfaces and Base Classes
Explicit Interface Implementations
Default Interface Methods
Supporting Default Interface Methods
Should I Use Default Interface Methods?
28 Structs
Memory and Constructors
Classes vs. Structs
Choosing to Make a Class or a Struct
Rules to Follow When Making Structs
Built-In Type Aliases
Boxing and Unboxing
29 Records
Records
String Representation
Value Semantics
Deconstruction
with Statements
Advanced Scenarios
Additional Members
Replacing Synthesized Members
Non-Positional Records
Struct- and Class-Based Records
Inheritance
When to Use a Record
30 Generics
The Motivation for Generics
Defining a Generic Type
Multiple Generic Type Parameters
Inheritance and Generic Types
Generic Methods
Generic Type Constraints
Multiple Constraints
Constraints on Methods
The default Operator
31 The Fountain of Objects
The Main Challenge
Expansions
32 Some Useful Types
The Random Class
The DateTime Struct
The TimeSpan Struct
The Guid Struct
The List Class
Creating List Instances
Indexing
Adding and Removing Items from List
foreach Loops
Other Useful Things
The IEnumerable Interface
The Dictionary Class
Types Besides string
Dictionary Keys Should Not Change
The Nullable Struct
ValueTuple Structs
The StringBuilder Class
Part 3: Advanced Topics
33 Managing Larger Programs
Using Multiple Files
Namespaces and using Directives
Advanced using Directive Features
Global using Directives
Static using Directives
Name Conflicts and Aliases
Putting Types into Namespaces
Namespace Naming Conventions
Traditional Entry Points
34 Methods Revisited
Optional Arguments
Named Arguments
Variable Number of Parameters
Combinations
Passing by Reference
Output Parameters
There’s More!
Deconstructors
Extension Methods
35 Error Handling and Exceptions
Handling Exceptions
Handling Specific Exception Types
Using the Exception Object
Throwing Exceptions
The finally Block
Exception Guidelines
What to Handle
Only Handle What You Can Fix
Use the Right Exception Type
Avoid Pokémon Exception Handling
Avoid Eating Exceptions
Avoid Throwing Exceptions When Possible
Come Back with Your Shield or On It
Advanced Exception Handling
Stack Traces
Rethrowing Exceptions
Inner Exceptions
Exception Filters
36 Delegates
Delegate Basics
The Action, Func, and Predicate Delegates
MulticastDelegate and Delegate Chaining
37 Events
C# Events
Events with Parameters
Null Events
Event Leaks
EventHandler and Friends
Custom Event Accessors
38 Lambda Expressions
Lambda Expression Basics
The Origin of the Name Lambda
Multiple and Zero Parameters
When Type Inference Fails
Discards
Lambda Statements
Closures
39 Files
The File Class
String Manipulation
Other String Parsing Methods
File System Manipulation
The Directory Class
The Path Class
There’s More!
Other Ways to Access Files
Streams
Find a Library
40 Pattern Matching
The Constant Pattern and the Discard Pattern
The Monster Scoring Problem
The Type and Declaration Patterns
Case Guards
The Property Pattern
Nested Patterns
Relational Patterns
The and, or, and not Patterns
The Positional Pattern
Deconstructors and the Positional Pattern
The var Pattern
Parenthesized Patterns
Patterns with Switch Statements and the is Keyword
Switch Statements
The is Keyword
Summary
41 Operator Overloading
Operator Overloading
Defining an Operator Overload
When to Overload Operators
Indexers
Index Initializer Syntax
Custom Conversions
The Pitfalls of Custom Conversions and Some Alternatives
42 Query Expressions
Queries and IEnumerable
Sample Classes
Query Expression Basics
Filtering
Ordering
Method Call Syntax
Unique Methods
Advanced Queries
Multiple from Clauses
Joining Multiple Collections Together
The let Clause
Continuation Clauses
Grouping
Group Joins
Deferred Execution
LINQ to SQL
43 Threads
The Basics of Threads
Using Threads
Sharing Data with a Thread
Sleeping
Thread Safety
Locks
44 Asynchronous Programming
A Sample Problem
Threads and Callbacks
Using Tasks
Task and Task Basics
The async and await Keywords
Who Runs My Code?
Some Additional Details
Exceptions
Cancellation
Awaitables
Limitations
More Information
45 Dynamic Objects
Dynamic Type Checking
Dynamic Objects
Emulating Dynamic Objects with Dictionaries
Using ExpandoObject
Extending DynamicObject
When to Use Dynamic Object Variations
46 Unsafe Code
Unsafe Contexts
Pointer Types
Fixed Statements
Stack Allocations
Fixed-Size Arrays
The sizeof Operator
The nint and nuint Types
Calling Native Code with Platform Invocation Services
47 Other Language Features
Iterators and the yield Keyword
Async Enumerables
Constants
Attributes
Attributes on Everything
Attributes are Classes
Reflection
The nameof Operator
Nested Types
Even More Accessibility Modifiers
Bit Manipulation
Bitshift Operators
Bitwise Logical Operators
Flags Enumerations
using Statements and the IDisposable Interface
Preprocessor Directives
#warning and #error
#region and #endregion
Working with Conditional Compilation Symbols
Command-Line Arguments
Partial Classes
Partial Methods
The Notorious goto Keyword
Generic Covariance and Contravariance
Checked and Unchecked Contexts
Volatile Fields
48 Beyond a Single Project
Outgrowing a Single Project
NuGet Packages
49 Compiling in Depth
Hardware
Assembly
Programming Languages
Instruction Set Architectures
Virtual Machines and Runtimes
50 .NET
The History of .NET
The Components of .NET
Common Infrastructure
Common Intermediate Language
The Common Language Runtime
The .NET Software Development Kit
Base Class Library
App Models
Web App Models
Mobile App Models
Desktop App Models
Game Development
51 Publishing
Build Configurations
Publish Profiles
.pubxml Files
Publishing with a Profile
After Publishing
Part 4: The Endgame
52 The Final Battle
Overview
Core Challenges
Expansions
53 Into Lands Uncharted
Keep Learning
Other Frameworks and Libraries
Other Topics
Make Software
Do the Side Quests
Where Do I Go to Get Help?
Parting Words
Part 5: Bonus Levels
A Visual Studio Overview
Windows
The Code Window
Code Navigation
IntelliSense
Quick Actions
The Solution Explorer
The Properties Window
The Error List
Other Windows
The Options Dialog
B Compiler Errors
Code Problems: Errors, Warnings, and Messages
How to Resolve Compiler Errors
Compile Often
Use a Quick Action
Make Sure You Understand the Key Parts of the Error Message
Backup or Undo
Be Cautious with Internet Code
Be Careful Transcribing Code
Fix the Errors that Make Sense
Look Around
Take a Break
Read the Documentation
Ask for Help
Common Compiler Errors
“The name ‘x’ doesn’t exist in the current context”
“) expected”, “} expected”, “] expected”, and “; expected”
Cannot convert type ‘x’ to ‘y’
“not all code paths return a value”
“The type or namespace name ‘x’ could not be found”
C Debugging Your Code
Some Broken Sample Code
Print Debugging
Using a Debugger
Breakpoints
Stepping Through Code
Edit and Continue and Hot Reload
Breakpoint Conditions and Actions
Glossary
Index