C# Cheatsheet — Quick Reference
C# 12 (with .NET 8) syntax, OOP, LINQ, and the most commonly used standard library—a cheatsheet covering about 80% of everyday scenarios.
C# C# 12 (with .NET 8)
.NET (Core / 5+ / 8) · OOP, generics, functional, concurrent · Static, strong typing, nominal typing
Recommended Learning Path
First, get 'Hello World and Build Environment' running (dotnet new console) → familiarize yourself with variables, types, and control flow → process data with collections and LINQ → understand object-oriented programming (class/interface) → master async/await → finally look up files, networking, regex, and build/debugging as needed. The FAQ section is worth revisiting to avoid pitfalls.
1.Hello World and Build Environment
Create, run, and organize a .NET program from scratch: top-level statements, project files, namespaces, and command-line arguments.
Minimal Program
C# 9+ supports top-level statements: write executable code directly in Program.cs with no class and Main boilerplate. Console.WriteLine prints a line.
Create and Run
The dotnet CLI is the command-line entry point for .NET: dotnet new creates a project, dotnet run compiles and runs, dotnet build only compiles.
Command-Line Arguments
In top-level statements, args is a string[] of command-line arguments, with user parameters starting at args[0]. Equivalent to the traditional Main(string[] args).
Exit Code
Top-level statements can use return to specify an exit code: 0 means success, non-zero indicates an error category. Environment.ExitCode can also be read and written.
Namespace
namespace organizes types to avoid collisions. File-scoped namespaces (C# 10) are declared with a semicolon, omitting braces and indentation.
using Directive
The using directive imports a namespace, removing the need for fully qualified names. Global usings in GlobalUsings.cs are shared across the project.
Top-Level Statement Details
Top-level statements compile into the Main method of a Program class. Only one per project is allowed; use local functions for helpers.
csproj Project File
The csproj file is project configuration: TargetFramework, ImplicitUsings, and Nullable enable the nullable context.
2.Variables and Constants
Type inference, const/readonly, nullable types, null-coalescing, nameof, and scope.
var Type Inference
var lets the compiler infer the type from the initializer. Local variables can be inferred, but fields/properties cannot. Prefer var when the initializer's type is clear for brevity.
const and readonly
const is a compile-time constant (primitive types); readonly is a runtime read-only field (assignable in a constructor). For static constants, prefer static readonly.
Nullable Types
Nullable<T> (e.g., int?) allows value types to be null; nullable reference types (? suffix + Nullable enable) let the compiler statically analyze null references.
Null-Coalescing and Null-Conditional
?? returns the right side when the left side is null; ?.> short-circuits to null when the left side is null. Chained ?. makes deep access null-safe.
nameof Expression
nameof returns the symbol name as a string, automatically syncing on renames. Commonly used for parameter validation, property change notifications, and log tags.
Scope
C# uses braces to define block scope. Local variables can shadow fields with the same name (avoid for clarity); using declarations restrict resource scope to the block's end.
init and Property Initialization
The init accessor allows assignment in object initializers and is read-only afterward. Property initializers set defaults; the set accessor can add validation.
Deconstruction
Tuples and records support deconstruction: use parentheses to split elements into multiple variables. The Deconstruct method customizes deconstruction logic.
3.Data Types
Built-in types, nullable, enum, struct, generics, record, tuple, and type conversion.
Built-in Types
Built-in types like int/long/double/bool map to System types. var is just inference; the runtime type is unchanged.
Nullable Types
int? is a nullable value type (Nullable<int>); access via HasValue/Value. With Nullable enable, the compiler statically checks nullable reference types.
enum
enum defines named integer constants, defaulting to int. The Flags attribute enables bit combinations to be tested with HasFlag or bitwise operations.
struct
struct is a value type: assignment copies the whole block, allocated on the stack, and cannot be null (boxed when made nullable). Use struct for small, immutable data.
Class (Reference Type)
class is a reference type: assignment shares the same object, GC manages memory, can be null. Use class for mutable state.
Generics
Generics parameterize types, generating strongly typed code at compile time without runtime boxing. T is the type parameter; the where clause adds constraints.
record Type
record (C# 9) is a reference type with value semantics: built-in value equality, ToString, deconstruction, and with expressions. Suited for DTOs and immutable data.
Tuple
Tuples pack multiple values and support named elements. Most convenient for returning multiple values or quick aggregations; use tuples short-term, record long-term.
Type Conversion
is safely checks type, as safely casts (returns null on failure), (T) is a hard cast (throws on failure), Convert/Parse explicitly parses.
Pattern Matching
is/switch use pattern matching: type patterns, property patterns, positional patterns. Replaces lots of if + cast, expressing intent more clearly.
4.References and Arrays
Value types vs reference types, arrays, Span, index/range, ref/in/out, and unsafe pointers.
Value Type vs Reference Type
Value types (struct/enum/primitives) are copied on assignment; reference types (class/interface) share the object on assignment. This is C#'s most important mental model.
Arrays
Arrays are fixed-length reference types, accessed with [] indexing. Multidimensional and jagged arrays differ: [,] is rectangular, [][] is jagged. Arrays use Length, not Count.
Index and Range
^ indexes from the end (^1 is the last), .. denotes a range (1..^1 excludes first and last). Modern syntax for slicing arrays/Lists.
Span and Memory
Span<T> is a read-only view over any contiguous memory, allocation-free and sliceable, the core of high-performance data processing. Can point to stack or heap memory.
ref / in / out Parameters
ref passes by reference (read-write), in passes by reference (read-only), out is for return values (callers don't need to initialize first). Pass-by-reference avoids copying value types.
unsafe Pointers
unsafe context allows real pointers (e.g., int*); requires AllowUnsafeBlocks in csproj. Use only for native interop; avoid in ordinary code.
Memory and Buffers
Memory<T> is the heap-safe version of Span, storable in fields and usable across async. ReadOnlyMemory is the read-only view. Used for async buffered data processing.
Copy Semantics
Value types are passed by value by default (large structs incur copy overhead); objects (references) are passed by reference. Use ref only when you need to modify in place.
5.Control Flow
if/else, for/foreach/while, switch expressions, break/continue, and throw expressions.
if / else
if/else branches on a condition. C# uses == for comparison, && and || for short-circuit. Braces can be omitted for a single statement but it's recommended to keep them.
for Loop
Classic for: initializer, condition, step. Use when you need an index; foreach is safer in most cases.
foreach Iteration
foreach iterates collections without an index, with compile-time safety. Combined with var and LINQ, it's the most common way to process data.
while / do-while
while checks first then executes; do-while executes at least once. Use when reading streams until EOF or for unknown loop counts.
switch Expression
The switch expression (C# 8) uses => to return a value, replacing long if-else chains. Type patterns combined with when guards are powerful.
break and continue
continue skips to the next iteration; break exits the loop; return exits the method. Use goto to escape from nested loops.
Ternary Operator
cond ? a : b expresses an if/else assignment in one line. Branch expression types must be compatible (convertible to a common type).
throw Expression
throw can be used as an expression on the right side of ?? and ?:, and as a single-line method body. Throwing ArgumentNullException is concise for parameter validation.
6.Functions and Methods
Method signatures, parameter passing, overloading, local functions, lambda, and expression-bodied members.
Method Definition
A method = return type + name + parameter list + body. Returning void means no return value. Access modifiers control visibility.
Parameter Passing
Pass by value by default: modifications inside the method don't affect the caller's variable. Objects are passed as a reference copy; modifying members affects the original.
Optional and Named Parameters
Optional parameters have default values (must be at the end of the parameter list); named arguments pass by name, skipping intermediate optional parameters.
ref / out / in
ref passes by reference (read-write); out is for output only (no pre-initialization needed); in passes by reference read-only (avoids large value-type copies).
Method Overloading
Overloading = same method name with different parameter lists (count/type). The compiler picks the best match based on arguments. Return type doesn't participate in overload resolution.
Expression-Bodied Members
When a method/property/constructor is a single expression, use => as shorthand. Similar to lambda, but expression-bodied members are real members.
Local Functions
Functions defined inside a method can access outer variables (closures); commonly used for recursive helpers or iterator internals.
Lambda Expression
Anonymous function: arguments => expression. Used with delegate/Func/Action, this is LINQ's core syntax.
Delegate
A delegate is a method type: declare a signature, subscribe multiple methods with +=, invoking the delegate triggers them in order. Events are based on delegates.
7.Strings
String literals, interpolation, common methods, mutable StringBuilder, and formatting.
String Literals
Double-quoted regular strings, @ verbatim strings (escape sequences are not processed), $ interpolated strings, and $$ composite literals (C# 11).
String Interpolation
The $ prefix inlines the result of expressions in {} into the string; supports formatting and alignment. More readable than + concatenation.
Concatenation and Comparison
+ concatenates, string.Concat batches, string.Join uses separators. String equality uses == (value comparison), not the quote operator.
Common Methods
Length, Substring, Contains, StartsWith, IndexOf, Replace, Trim, Split, ToUpper/ToLower cover the vast majority of string processing.
StringBuilder
Use StringBuilder for heavy concatenation to avoid repeatedly creating strings (strings are immutable; + creates a new object each time). Especially noticeable in loops.
char
char is a single UTF-16 character. char.IsDigit/IsLetter/IsWhiteSpace checks categories. string is immutable; char is iterable.
Formatting
string.Format / $ interpolation use format specifiers: D for integer, F for decimal, C for currency, P for percentage, X for hexadecimal.
Parsing Strings
Parse converts a string to a number (throws on failure); TryParse is safe (returns bool + out result). Prefer TryParse.
8.Collections and LINQ
Common collections like List/Dictionary/HashSet, IEnumerable, and chained LINQ queries.
List Dynamic Array
List<T> is a variable-length array: Add/Insert/Remove/IndexOf, O(1) index access. Iterate with foreach.
Dictionary
Dictionary<K,V> maps keys to values with O(1) lookup. TryGetValue is safe for retrieval; iterate KeyValuePair.
HashSet
HashSet<T> has no duplicates and O(1) Contains checks. UnionWith/IntersectWith/ExceptWith perform set operations for dedup and merging.
Queue and Stack
Queue<T> is FIFO (Enqueue/Dequeue); Stack<T> is LIFO (Push/Pop). Use for task queues or undo stacks.
IEnumerable and Laziness
IEnumerable<T> is a read-only sequence interface; LINQ uses it for lazy evaluation: values are computed when iterated. Arrays/Lists/Dictionaries all implement it.
LINQ Filtering and Projection
Where filters, Select projects (maps), OrderBy sorts, Distinct dedupes. Method chains are readable and lazy.
LINQ Aggregation
Count/Sum/Average/Min/Max aggregate; Any/All test; First/Single pick an element (throw on no match; FirstOrDefault returns default).
GroupBy
GroupBy groups by key, producing IGrouping sequences; commonly used for statistics (count, sum by category).
LINQ Query Syntax
The from/where/orderby/select query syntax is declarative for method chains and is equivalent after compilation. A matter of readability preference.
9.Memory and Resource Management
Automatic GC, IDisposable and using to release unmanaged resources, weak references, and object pools.
GC Garbage Collection
C# memory is managed by the GC automatically: heap objects are collected when no longer referenced. Generational collection (0/1/2) optimizes performance.
IDisposable Interface
Classes that hold unmanaged resources (files/network/database connections) implement IDisposable, releasing resources in Dispose.
using Statement and Declaration
using ensures Dispose is called at the end of the scope (finally semantics). The using declaration (C# 8) automatically releases resources when the block ends.
Finalizer
The destructor ~Class() is the finalizer: called before GC reclaims the object, with no guaranteed timing. Use only for unmanaged resources; normally follow the Dispose pattern.
Weak Reference
WeakReference doesn't prevent the GC from collecting the target; used for caches (dictionary caching heavy objects, allowing reclamation). Target may become null at any time.
Object Pool and ArrayPool
For frequent large array allocations, use ArrayPool to reuse buffers and reduce GC pressure. Pair ArrayPool<T>.Shared.Rent with Return.
stackalloc Stack Allocation
stackalloc allocates memory on the stack: fast and doesn't trigger GC; suited for small temporary buffers. Stack space is limited, so use with caution.
GC Memory Pressure
When allocating large amounts of native memory, use GC.AddMemoryPressure to inform the GC, prompting timely collection of managed objects and preventing uncontrolled memory growth.
10.Object-Oriented Programming
Classes, properties, constructors, inheritance, polymorphism, interfaces, abstract classes, and access modifiers.
Class and Object
class defines a data type (reference type). Fields hold state, properties control access, methods define behavior, constructors initialize.
Properties
Properties are safe accessors for fields: get reads, set writes; access modifiers and validation logic can be added. The compiler generates backing fields.
Inheritance
C# supports single inheritance: class uses : to inherit a base class. A derived class is-a base class. Private members aren't inherited; protected members are accessible.
Polymorphism
virtual + override enables polymorphism: the method called via a base reference dispatches to the actual type. A method must be virtual to be overridden.
Abstract Class
An abstract class can't be instantiated and may contain abstract methods (subclasses must implement). Abstract methods have no body. Used for template base classes.
Interface
interface defines a contract: members have no implementation; implementing classes must provide them. C# supports multiple interface implementation (an alternative to multiple inheritance).
Access Modifiers
public is open, private is closed, protected is visible to derived classes, internal is visible within the assembly. Defaults: class is private, members are private.
sealed and object Methods
sealed classes can't be inherited; sealed override methods can't be overridden further. All classes implicitly inherit object (ToString/Equals/GetHashCode).
Static Class and Extension Methods
static class can only contain static members and can't be instantiated. Extension methods are static methods in a static class; a this parameter lets them be called on instances.
11.Exception Handling
try/catch/finally, exception types, custom exceptions, the cost of exceptions, and best practices.
try / catch / finally
try holds code that may fail; catch handles it; finally runs regardless of success or failure (cleanup). Exceptions propagate upward.
Multiple catch and Exception Filters
Multiple catch clauses match by type, with more specific ones first. when provides a filter condition. Catch without a variable ignores the exception object.
Throwing Exceptions
throw new throws an exception; throw; (no argument) rethrows as-is (preserving the stack). throw new inside a catch resets the stack.
Custom Exceptions
Custom exceptions inherit from Exception (conventionally with an Exception suffix), provide constructors, and preserve the inner exception via InnerException.
finally Cleanup
finally guarantees resource release/state restoration regardless of whether try throws. return runs finally first. using is its syntactic sugar.
Cost of Exceptions
Exception catching is expensive; don't use exceptions for control flow. For predictable errors, use return codes, TryXxx, or the Result pattern.
Global Exception Handling
Use try/catch at the top level to catch unhandled exceptions and log them. In ASP.NET, use middleware (UseExceptionHandler) for unified handling.
InnerException Chain
After catching an exception, throw a new one passing the original as InnerException, preserving the full error chain—more valuable for log diagnosis.
12.Files and I/O
Static File/Directory/Path utilities, Stream read/write, async I/O, and binary handling.
Reading and Writing Text Files
File.ReadAllText/WriteAllText read/write small files in one go; ReadAllLines returns a line array. Use StreamReader for large files.
StreamReader Line by Line
Large files are read line by line in a streaming manner, not consuming memory. StreamReader.ReadLine loops until null (end of file).
Directory Operations
Directory creates/deletes/enumerates directories; Directory.GetFiles/EnumerateFiles find files. Use SearchOption for recursive enumeration.
Path Handling
Path joins/parses paths cross-platform: Combine, GetExtension, GetFileName, ChangeExtension. Don't handcraft path separators.
Async I/O
async/await I/O doesn't block threads: ReadAllTextAsync/WriteAllTextAsync/Stream methods. Required for UI/server concurrency.
Binary Read/Write
BinaryWriter/BinaryReader read/write by type; MemoryStream is an in-memory stream. Common in network and file binary protocols.
Console I/O
Console.ReadLine reads a line, ReadKey reads a keystroke, WriteLine outputs. Redirect Console.In/Out streams for testability.
File Information
FileInfo/DirectoryInfo provide file metadata and methods; File.Exists checks existence; GetCreationTime returns timestamps.
13.Common Pitfalls (FAQ)
The most common pitfalls C# developers fall into: value vs reference, string equality, LINQ laziness, async/await deadlocks, and more.
String == vs Equal
C#'s string == compares by value (unlike Java). But == uses ordinal comparison; Equals can specify StringComparison for case-insensitive matching, etc.
Pass by Value vs Pass by Reference
Method parameters are passed by value by default: objects pass a reference copy (modifying members affects the original); value types copy. Forgetting this is a common bug.
LINQ Lazy Evaluation
LINQ queries are lazy: nothing is computed until enumerated. Passing IQueryable/IEnumerable out and enumerating later may cause side effects or stale data.
async void and Deadlocks
Event handlers may use async void; ordinary methods must return Task. In sync contexts (UI/WinForms), .Result/.Wait() can deadlock.
Swallowing and Rethrowing Exceptions
Catching without handling silently swallows; throw ex resets the stack, losing the original chain. Logs must preserve InnerException.
Unreleased Resources
Failing to release Stream/HttpClient/database connections leaks resources. Always use using with IDisposable, or call Dispose after use.
Floating-Point Comparison
float/double have imprecise binary representation; direct == comparison yields surprises. Use an epsilon tolerance or decimal for exact arithmetic.
Modifying Collections During Iteration
Adding/Removing a collection inside foreach throws InvalidOperationException. Collect elements to remove, then delete after iteration.
Nullable and Null Reference
With Nullable enabled, the compiler helps catch null references. Avoid the ambiguity of returning null directly; use ?? / ?. for fallbacks.
Local Time vs UTC
Store/transfer time in UTC (DateTimeKind.Utc); convert to local when displaying. Mixing Kinds silently miscalculates time.
14.Concurrency and Async
Task-based async programming, Parallel parallelism, lock synchronization, and thread-safe collections.
async / await
async methods return Task; await yields the thread and resumes after completion. The thread is freed for other work in between—no blocking.
Task and Return Values
Task represents an async operation; Task<T> carries a return value. Task.Run puts synchronous work on the thread pool; ContinueWith chains.
Parallel
Parallel.For/ForEach use the thread pool to execute independent work in parallel. CPU-intensive tasks leverage multiple cores; mind thread safety and over-parallelism.
lock Synchronization
lock ensures only one thread enters the critical section at a time. Lock objects are usually private readonly fields; avoid locking on this.
Thread
Thread manually manages threads: Start to begin, Join to wait. Task/Parallel fit most scenarios; Thread is for long-running background tasks.
CancellationToken
CancellationToken is cooperative cancellation: the token triggers IsCancellationRequested, and async methods throw OperationCanceledException.
Concurrent Collections
Thread-safe collections: ConcurrentDictionary, ConcurrentQueue, ConcurrentBag. Replace manually locking reads/writes on regular collections.
Async Best Practices
Async all the way: don't block on .Result. ConfigureAwait(false) in library code avoids returning to the sync context.
15.Networking and HTTP
HttpClient for requests, JsonSerializer for serialization, WebSocket, and Socket.
HttpClient Basics
HttpClient sends HTTP requests. GetStringAsync for simple text, GetAsync for full responses. HttpClient should be reused long-term (singleton).
POST and JSON
PostAsJsonAsync sends JSON; PostAsync sends custom content. Read responses with ReadAsStringAsync. JsonSerializer handles serialization.
Headers and Query Parameters
HttpRequestMessage sets Headers (auth/User-Agent); URI builds query strings. Note: some APIs reject the default User-Agent.
System.Text.Json
JsonSerializer.Serialize/Deserialize handles JSON. JsonSerializerOptions configures casing, enums, and ignoring null.
Calling Web APIs
Composition: build request → check status → deserialize. HttpStatusCode checks; ReadFromJsonAsync does it in one line.
WebSocket
ClientWebSocket establishes a full-duplex channel; SendAsync/ReceiveAsync send/receive. Ideal for real-time push (chat, quotes).
DNS and Socket
Dns.GetHostAddresses resolves hostnames; Socket is the low-level transport. Most apps only need HttpClient; Socket is for custom protocols.
Download and Stream Processing
Download large files via Stream for streaming writes, avoiding large memory use. HttpCompletionOption.ResponseHeadersRead returns the stream immediately.
16.Date and Time
DateTime and TimeSpan, time zones and offsets, formatting and parsing.
DateTime Basics
DateTime represents a date-time: Now is local, UtcNow is UTC, Today is the date. AddDays/AddHours perform date arithmetic.
TimeSpan
TimeSpan represents an interval: get it by subtracting two times, build with FromDays/FromHours, decompose into Days/Hours.
DateTimeOffset
DateTimeOffset carries a time zone offset; recommended for cross-zone scenarios. Safe conversion to/from UTC, avoiding local-time ambiguity.
DateTimeKind
DateTime has a Kind: Unspecified/Local/Utc. Local time without a specified Kind will misbehave when converting to UTC; store as Utc.
Parsing and Formatting
DateTime.Parse/ParseExact parse; TryParse is safe. Format tokens: yyyy/MM/dd, HH:mm:ss, ffff for milliseconds.
Time Zone Conversion
TimeZoneInfo performs time zone conversion: FindSystemTimeZoneById, ConvertTimeFromUtc. Servers usually store UTC; convert to local for display.
Stopwatch Timing
Stopwatch is for high-precision timing (millisecond resolution). Start/Stop/Elapsed/ElapsedMilliseconds are the standard for performance measurement.
DateOnly and TimeOnly
DateOnly represents only a date; TimeOnly only a time (C# 10), free of time zone concerns—ideal for birthdays, calendars, and scheduling.
17.Processes and System
Launching external processes, environment variables, paths, and system information.
Launching Processes
Process.Start launches an external program (shell command, other executable). ArgumentList passes arguments safely, avoiding injection from concatenation.
Environment Variables
Environment.GetEnvironmentVariable reads; SetEnvironmentVariable writes (process-level). GetEnvironmentVariables returns all.
System Information
Environment provides system info: OSVersion, MachineName, CurrentDirectory, ProcessorCount, TickCount.
Command-Line Parsing
args carries command-line arguments; Environment.GetCommandLineArgs gets the full set (including program name). For CLI tools, parse arguments.
Exit and Signals
Environment.Exit(1) exits immediately; ExitCode sets the exit code. The AppDomain.ProcessExit event runs cleanup.
Enumerating Processes
Process.GetProcesses enumerates system processes, reading Id/ProcessName/WorkingSet64, etc.; Kill terminates a process.
Windows Registry
Microsoft.Win32.Registry reads/writes the registry (Windows only). GetValue/SetValue access keys; appropriate permissions are required.
Application Path
AppContext.BaseDirectory is the program's running directory; Environment.ProcessPath is the current process path. Use them to locate resource files.
18.Regular Expressions
Regex matching, capture groups, replacement, and common patterns.
Regex Basics
Regex.IsMatch tests; Matches finds all; Match finds the first. Use @ verbatim strings to avoid double-escaping.
Capture Groups
Parentheses capture substrings; Groups[1] for indexed, named groups (?<name>...) via Groups["name"]. Used to extract fields.
Replacement
Regex.Replace replaces with patterns; $1/$2 reference capture groups. Useful for formatting, masking, and cleaning text.
RegexOptions
RegexOptions.IgnoreCase ignores case, Multiline makes ^/$ match per line, Compiled speeds up repeated use.
Common Patterns
Common regex patterns for email, URL, IP, phone numbers. Note: for complex validation (e.g., real email), use a dedicated library instead of regex.
Quantifiers and Anchors
* zero or more, + one or more, ? zero or one, {n,m} specific count; ^ start of line, $ end of line, \b word boundary.
Assertions and Lookaround
Zero-width assertions don't consume characters: (?<=...) lookbehind, (?=...) lookahead, (?!...) negative lookahead; match position conditions.
Backtracking and ReDoS
Nested quantifiers and alternation cause backtracking; malicious input can trigger exponential matching (ReDoS). Limit timeouts or disable backtracking.
19.Build and Debug
dotnet CLI, project configuration, debugging, logging, and conditional compilation.
dotnet CLI
dotnet build compiles, run runs, test tests, publish publishes. --configuration Release builds a release configuration.
csproj Configuration
csproj controls the build: TargetFramework, Nullable, ImplicitUsings, PackageReference dependencies, LangVersion.
Debugging and Logging
Debug.WriteLine only in Debug builds; Trace works in all builds. ILogger records log levels. Console.WriteLine for temporary debugging.
Conditional Compilation
#if DEBUG / #elif / #endif trims code by symbol. Project-level DefineConstants defines custom symbols.
Unit Tests
xUnit/NUnit/MSTest assert behavior. [Fact] is a test method; Assert.Equal asserts. dotnet test runs them.
NuGet Package Management
dotnet add package adds dependencies; restore restores them. PackageReference records versions in csproj.
Publishing and Single File
dotnet publish produces a production version; PublishSingleFile packages a single file; SelfContained requires no runtime install.
Static Analyzers
Roslyn analyzers check code quality and potential defects at compile time; warnings can be escalated to errors to block problematic builds.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained cheatsheet for C# 12 (.NET 8), covering about 80% of the language core, common BCL types, and async programming in real-world projects. The content leans toward modern idioms: properties and auto-properties, LINQ, async/await, record types, pattern matching, nullable reference types. C# was introduced by Anders Hejlsberg in 2000 alongside the .NET platform, and is the core language of the Windows ecosystem, Unity game development, and backend services, emphasizing a harmony of type safety and productivity. 19 sections each focus on one topic: basic syntax, variables, types and reference/value semantics, control flow, functions, strings, collections, memory management (GC), object-oriented programming, error handling, I/O, common pitfalls, concurrency, networking, time, processes, regex, and build tools. Each subsection includes a concept introduction plus a directly copyable code snippet. All code and text are rendered locally in the browser; no data leaves your device. For authoritative references, see the official Microsoft Learn documentation.
Version 2.1.0