Skip to content
Tutorials Center
My learning

Topics

Lesson 178 of 182 ยท Practice and Review

C# Cheat Sheet

A one-page C# 14 cheat sheet with tables for syntax, types, collections, LINQ, async and modern idioms, plus runnable snippets you can edit and test.

This page is the quick reference for the whole C# tutorial. It is not a replacement for the lessons: each row links to the place where the idea is explained in depth. Use it when you know what you want to do but have forgotten the exact spelling, the right collection, or the name of the LINQ operator.

Everything below assumes modern C# (C# 14 on .NET 10) with nullable reference types and implicit usings turned on, which is how every example on this site runs. Four of the sections end with a small program you can edit in the browser, so you can check a row of a table in seconds.

Program shape and syntax

Task Spelling Learn more
Hello world Console.WriteLine("Hi"); (top-level statements) Program structure
Explicit entry point static async Task Main(string[] args) Program structure
Namespace namespace Shop.Orders; (file-scoped) Syntax
Local variable var total = 0m; or decimal total = 0; Variables
Constant const int Max = 10; (compile time) Constants
Read-only field private readonly List<int> _items = []; Constants
String interpolation $"{name,-8}|{price:N2}" Interpolation
Raw string """ ... """ (no escaping needed) Raw strings
Comment / XML doc // note, /// <summary>...</summary> Comments
Naming PascalCase types and members, camelCase locals, _camelCase private fields, IName interfaces Syntax

Types and conversions

Type Notes
int, long, byte, short Integers of 32, 64, 8 (unsigned) and 16 bits. Overflow wraps unless you use checked.
uint, ulong, sbyte, ushort Unsigned and rarely used variants.
double, float Binary floating point; never compare with ==.
decimal Base-10 floating point, use for money. Suffix m.
bool, char true/false; one UTF-16 code unit.
string Immutable sequence of UTF-16 chars; use StringBuilder for many appends.
object, dynamic Root of all types; dynamic skips compile-time checks.
int?, string? Nullable value type (Nullable<int>) and nullable reference annotation.
(int X, int Y) Value tuple with names.
enum, struct, record, record struct, class The five ways to declare your own type.
Conversion Spelling
Widening (safe) long l = 5; implicit
Narrowing int i = (int)3.9; explicit, truncates to 3
Parse, may throw int.Parse("42")
Parse, no exception int.TryParse(text, out int n)
Test and cast obj is string s, obj as string
Overflow check checked(a + b) throws OverflowException

Operators and control flow

Need Spelling
Null fallback name ?? "unknown"
Null-safe member user?.Address?.City
Null-safe assignment (C# 14) user?.Name = "Mia";
Assign if null cache ??= new();
Ternary x > 0 ? "pos" : "non-pos"
Switch expression n switch { < 0 => "neg", 0 => "zero", _ => "pos" }
Range / index arr[1..^1], arr[^1]
Loops for, foreach, while, do ... while
Early exit break, continue, return

Methods and members

Need Spelling
Expression-bodied int Square(int x) => x * x;
Optional / named args Send(to, retries: 3)
Output parameter bool TryGet(int id, out Item item)
params collection int Sum(params ReadOnlySpan<int> xs)
Lambda x => x * 2, (a, b) => a + b
Local function int Twice(int x) => x * 2; inside a method
Auto-property public string Name { get; init; }
Required member public required string Id { get; init; }
Primary constructor class Point(int x, int y)
Record record Person(string Name, int Age);
field keyword (C# 14) set => field = value.Trim();
Extension method static int Words(this string s)

Collections

Collection Use it when Lookup Add
T[] Fixed size, fastest O(1) by index not possible
List<T> Default growable list O(1) by index, O(n) search O(1) amortized at the end
Dictionary<K,V> Key to value O(1) average O(1) average
HashSet<T> Unique items, set math O(1) average O(1) average
SortedDictionary<K,V> Keys in order O(log n) O(log n)
SortedSet<T> Unique items in order O(log n) O(log n)
Queue<T> First in, first out peek O(1) O(1)
Stack<T> Last in, first out peek O(1) O(1)
PriorityQueue<T,P> Smallest priority first peek O(1) O(log n)
LinkedList<T> Cheap inserts at a known node O(n) O(1) at a node
FrozenDictionary<K,V> Built once, read many times fastest reads not possible
ImmutableList<T> Persistent snapshots O(log n) O(log n)
ConcurrentDictionary<K,V> Many threads O(1) average O(1) average

Collection expressions (C# 12) create any of them: List<int> xs = [1, 2, 3];, int[] all = [..xs, 4];. See Choosing the right collection.

LINQ

Operator Result Example
Where Filter xs.Where(x => x > 2)
Select Transform xs.Select(x => x * x)
SelectMany Flatten orders.SelectMany(o => o.Lines)
OrderBy, ThenBy Sort (stable) people.OrderBy(p => p.Age).ThenBy(p => p.Name)
GroupBy Groups words.GroupBy(w => w.Length)
CountBy, AggregateBy (.NET 9) Keyed counts and folds words.CountBy(w => w[0])
Index (.NET 9) (Index, Item) pairs foreach (var (i, x) in xs.Index())
Join, LeftJoin (.NET 10) Combine two sequences a.LeftJoin(b, ka, kb, (x, y) => ...)
Distinct, DistinctBy Remove duplicates people.DistinctBy(p => p.Email)
Take, Skip, Chunk Paging xs.Skip(20).Take(10)
Any, All, Contains Booleans xs.Any(x => x < 0)
Count, Sum, Min, Max, Average Aggregates xs.Sum()
First, FirstOrDefault, Single One element xs.FirstOrDefault(x => x > 5)
Zip Pair up names.Zip(ages)
ToList, ToArray, ToDictionary, ToLookup Materialize xs.ToDictionary(x => x.Id)

LINQ is lazy: a query runs when you enumerate it, and again each time you enumerate it. Call ToList() once if you need a snapshot. More in Deferred execution.

Async and concurrency

Need Spelling
Async method async Task<int> LoadAsync()
Wait without blocking var x = await LoadAsync();
Run work on the pool await Task.Run(() => Compute())
Wait for all await Task.WhenAll(tasks)
First to finish await Task.WhenAny(tasks)
Results as they finish (.NET 9) await foreach (var t in Task.WhenEach(tasks))
Delay await Task.Delay(100, token)
Cancellation CancellationTokenSource cts = new(TimeSpan.FromSeconds(2));
Mutual exclusion private readonly Lock _gate = new(); then lock (_gate) { ... }
Atomic counter Interlocked.Increment(ref _count)
Producer / consumer Channel.CreateBounded<T>(capacity)
Async sequence async IAsyncEnumerable<T> ReadAsync()

Rules of thumb: never use .Result or .Wait() on a task you could await, never write async void except for event handlers, and pass a CancellationToken through every layer.

Errors and resources

Need Spelling
Throw throw new ArgumentException("bad", nameof(x));
Guard clause ArgumentNullException.ThrowIfNull(x);
Catch catch (IOException ex) when (ex.HResult == 5)
Always run finally { ... }
Dispose using var file = File.OpenRead(path);
Async dispose await using var conn = Open();

Quick checks you can run

The first program touches several rows of the tables above at once. Change a value and predict the output before you run it.

C# Syntax, null handling and ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second program shows the collections table in action: the right collection makes the code both shorter and faster.

C# Choosing collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The third program is a LINQ tour: filter, project, group, count and page in one pipeline.

C# A LINQ tour

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last program covers async and the modern idioms from the tables.

C# Async, records and collection expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Keep this page open in a tab while you practice. When a row is not enough, follow its link: each lesson explains the reasoning, the pitfalls and the performance notes that a table cannot hold.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which spelling reads a value that may be null and falls back to a default?

    The null-coalescing operator ?? returns its right side when the left side is null. ??= assigns, ?. navigates members, and ! only silences the compiler.
  2. 2. You need unique items that are always enumerated in sorted order. Which collection fits best?

    SortedSet<T> stores each item once and keeps them ordered, at O(log n) per operation. HashSet<T> is faster but unordered.
  3. 3. When does a LINQ query such as xs.Where(x => x > 2) actually run?

    Most LINQ operators are lazy. The pipeline runs when you enumerate it (foreach, ToList, Count and so on), and it runs again on every new enumeration.
  4. 4. What does await Task.WhenAll(tasks) return for an array of Task<int>?

    WhenAll completes when every task has completed and returns the results in the same order as the input tasks, not the order in which they finished.

Summary

  • Use the tables here to recall spelling, then follow the links when you need the reasoning behind a row.
  • Prefer modern forms: top-level statements, file-scoped namespaces, records, collection expressions, primary constructors and pattern matching.
  • Choose the collection by the operation you repeat most: index, key lookup, uniqueness, order or first-in-first-out.
  • LINQ pipelines are lazy; materialize with ToList() when you need a stable snapshot.
  • Use async/await end to end, pass a CancellationToken, and avoid blocking on tasks.
  • Practice with the problem sets next, then test yourself with the interview questions.

Next: Practice Problems: Fundamentals