Cheatsheets
C#
Modern C#: records, LINQ, async/await, pattern matching, and nullable reference types.
Test yourself56 entries
Program structure & var6
Console.WriteLine("Hello");Top-level statements — a file's executable code with no Main boilerplate.
var count = 5;var — implicit local typing; the static type is still inferred and fixed.
namespace App;File-scoped namespace (C# 10) — no braces, less nesting.
global using System;Project-wide using (C# 10) — declare once, available everywhere.
using static System.Math;Import a type's static members: Sqrt(x) without Math.
#nullable enableTurn on nullable reference types for the file (usually project-wide).
Classes, records & properties7
public record Point(int X, int Y);Positional record — immutable value type semantics on a reference type.
public string Name { get; set; }Auto-property — compiler generates the backing field; init/required refine it.
public sealed class Svc { }sealed — forbid inheritance (faster virtual dispatch, clear intent).
public static class Helpers { }Static class — only static members, no instances (utility/extension home).
public Point(int x) { X = x; }Constructor; `: base(x)` / `: this()` chains to a base/another ctor.
public abstract class Shape { }Abstract base — can't instantiate; defines abstract members to override.
private readonly int _id;readonly field — assignable only in declaration or constructor.
Nullable reference types6
string? maybe = null;Nullable reference types — the compiler tracks which references may be null.
x?.Prop?.Method()Null-conditional — short-circuits to null instead of throwing.
a ?? bNull-coalescing — value of a if non-null, else b.
field ??= Compute();Null-coalescing assignment — assign only if currently null (lazy init).
if (x is not null) { }Idiomatic null test via pattern (clearer than != null).
ArgumentNullException.ThrowIfNull(arg);Guard clause helper — throws with the parameter name if null.
Pattern matching & switch6
obj switch { ... }Switch expression — returns a value, with exhaustiveness and rich patterns.
if (shape is Circle { R: > 0 } c)Type + property pattern with capture — test, destructure, and bind in one.
n is > 0 and < 100Relational + logical pattern (and/or/not) — readable range checks.
case int n when n > 0:Statement switch with a `when` guard clause.
var (x, y) = point;Deconstruction — split a tuple/record into variables.
list is [var first, .., var last]List pattern (C# 11) — match by position/length with a `..` slice.
Generics & interfaces6
class Box<T> where T : notnullGeneric type with a constraint — keep type safety without boxing or casts.
interface IRepo<T> { T? Get(int id); }Interface — a contract; supports default methods and can be implemented explicitly.
where T : class, new()Combine constraints: reference type with a public parameterless ctor.
interface IShape : IComparableInterface inheritance — compose smaller contracts.
class C : Base, IFoo, IBarSingle base class, many interfaces.
static abstract T Zero { get; }Static abstract member (C# 11) — enables generic math over numbers.
Collections & LINQ8
items.Where(x => x.Ok).Select(x => x.Id)LINQ — composable, lazy queries over any IEnumerable<T>.
var d = new Dictionary<string, int>();Dictionary<K,V> — O(1) keyed lookup; TryGetValue avoids double lookups.
var list = new List<int> { 1, 2, 3 };List<T> — growable array; Add/Remove/indexer, the everyday collection.
int[] a = [1, 2, 3];Collection expression (C# 12) — unified literal for arrays/lists/spans, with `..spread`.
items.FirstOrDefault(x => x.Id == 1)First match or default (null/0) — won't throw like First.
items.Any() / items.All(p)Existence/universal checks — short-circuit, return bool.
items.GroupBy(x => x.Cat)Group into IGrouping buckets keyed by a selector.
var set = new HashSet<int>();HashSet<T> — unique elements, O(1) Contains, set operations.
async / await & Task6
async Task<int> GetAsync()async/await — non-blocking I/O; await unwraps a Task and resumes after.
await Task.WhenAll(t1, t2)Run independent async ops concurrently, then await them all together.
await foreach (var x in stream)Consume an IAsyncEnumerable<T> (async streaming).
CancellationToken ctCooperative cancellation — pass it through and honor ct.ThrowIfCancellationRequested().
await using var x = ...;Async disposal — awaits DisposeAsync for IAsyncDisposable resources.
.ConfigureAwait(false)In library code, don't capture the context — avoids overhead/deadlocks.
IEnumerable, yield & disposal5
IEnumerable<int> Take(...) { yield return x; }Iterator method — yield produces a lazy, streaming sequence without a buffer.
using var f = File.OpenText(path);using declaration — deterministic Dispose() at end of scope (frees handles).
foreach (var x in items)Iterate any IEnumerable<T>; gets the enumerator and calls MoveNext/Current.
class C : IDisposableImplement Dispose() to release resources you own deterministically.
yield break;Stop the iterator early, ending the sequence.
Delegates, events, exceptions6
Func<int, int> sq = x => x * x;Func/Action/Predicate — built-in delegate types for passing behavior as data.
try { } catch (IOException ex) when (...) { }Structured exception handling with type filtering and `when` exception filters.
public event EventHandler<T> Changed;Event — multicast delegate others subscribe to with `+=` / `-=`.
Changed?.Invoke(this, args);Raise an event safely — null-conditional handles no subscribers.
throw new ArgumentException("bad", nameof(p));Throw with nameof(p) so the message tracks renames.
delegate int Op(int a, int b);Custom named delegate type (when Func/Action don't read well).