C# Cheat Sheet
Variables, strings, switch expressions, loops, methods, collections, classes, records, interfaces, exceptions, generics, LINQ, lambdas, async/await, JSON, patterns, tests and minimal APIs on one printable page.
Strings & input
| Syntax | What it does | Lesson |
|---|
$"Hi {name}, total {sum:F2}" | Interpolation with formatting | Strings |
s.Trim() s.ToUpper() s.Contains("x") | Common string methods | Strings |
s.Split(',') string.Join(", ", items) | Split and join | Strings |
s[^1] s[1..4] | Last character and ranges | Strings |
string? line = Console.ReadLine(); | Read a line of input | Input & Output |
Console.ReadLine() ?? "" | Default when input is null | Input & Output |
Control flow & methods
| Syntax | What it does | Lesson |
|---|
var s = ok ? "yes" : "no"; | Conditional operator | if & switch |
x switch { < 0 => "neg", 0 => "zero", _ => "pos" } | Switch expression with patterns | if & switch |
for (int i = 0; i < n; i++) foreach (var x in items) | Loops | Loops |
while (c) { } do { } while (c); break; continue; | Condition loops and control | Loops |
int Square(int x) => x * x; | Expression-bodied method | Methods |
void Log(string m, bool urgent = false) then Log("x", urgent: true) | Optional and named arguments | Methods |
(int Min, int Max) Range(...) | Return a tuple | Methods |
Types
| Syntax | What it does | Lesson |
|---|
class Account { private decimal balance; public void Deposit(decimal a) { } } | Class with encapsulated data | Classes & Objects |
public string Name { get; init; } public decimal Total => P * Q; | Properties | Properties & Constructors |
public Order(string c) { } class Order(string c) { } | Constructor and primary constructor | Properties & Constructors |
class Dog : Animal virtual override abstract | Inheritance | Inheritance & Polymorphism |
interface INotifier { void Send(string m); } | Interface | Interfaces |
record Product(string Name, decimal Price); p with { Price = 5 } | Record and with | Structs & Records |
enum Status { Pending, Paid } [Flags] | Enum | Enums |
try { } catch (IOException ex) { } finally { } throw; | Exceptions | Exceptions |
Advanced C#
| Syntax | What it does | Lesson |
|---|
T Max<T>(T a, T b) where T : IComparable<T> | Generic method with constraint | Generics |
items.Where(x => x > 0).Select(x => x * 2).ToList() | LINQ pipeline | LINQ |
GroupBy OrderBy FirstOrDefault Any Sum | Common LINQ methods | LINQ |
Func<int, int> f = x => x * 2; Action<string> log | Delegates and lambdas | Delegates & Lambdas |
public event EventHandler<T>? Changed; Changed?.Invoke(this, e) | Events | Delegates & Lambdas |
async Task<int> GetAsync() await Task.WhenAll(a, b) | async/await | async & await |
File.ReadAllText(p) Path.Combine(a, b) | Files and paths | Files & JSON |
JsonSerializer.Serialize(obj) Deserialize<T>(json) | JSON | Files & JSON |
x?.Name ?? "none" obj is { Total: > 100 } | Null operators and patterns | Nullable & Patterns |
[Fact] [Theory] Assert.Equal(expected, actual) | xUnit tests | Unit Testing |
app.MapGet("/items/{id:int}", (int id) => ...) | Minimal API endpoint | Minimal APIs |
How to use this C# cheat sheet
This C# cheat sheet collects the syntax you'll reach for most often, in the same order as the course: program structure, variables and types, strings, conditions and loops, methods, collections, classes, interfaces and records, exceptions, generics, LINQ, lambdas, async code, files and JSON, patterns, tests and minimal APIs. Each row links to the lesson that explains it with examples and common mistakes.
Keep it open while you practise. When you can't remember the shape of a switch expression, how TryGetValue works, or which LINQ method groups items, a quick look here is faster than a search. Type part of a keyword into the filter box to jump straight to it, or print the page and keep it beside your keyboard.
C# gotchas worth remembering
- Strings are immutable.
name.ToUpper() returns a new string and leaves name unchanged; assign the result if you want to keep it. Building a long string in a loop is faster with StringBuilder. - Integer division drops the remainder.
7 / 2 is 3. Make one side a double or decimal to get 3.5, and use decimal for money. - == on objects compares references. Two different class instances with the same data are not equal unless the class overrides equality. Records compare by value, which is one reason they're handy for data.
- Parse can throw.
int.Parse("abc") throws an exception. int.TryParse(text, out var n) returns false instead, which suits user input. - LINQ is lazy. A query isn't run until you loop over it or call
ToList(), Count() or similar. Calling it twice runs it twice. - Don't block on async code.
.Result and .Wait() can freeze UI apps and waste threads in web apps. Use await all the way up. - Nullable warnings are useful. With nullable reference types on,
string? may be null and string shouldn't be. Fix the warnings instead of silencing them with !. - Dispose what you open. Files, streams and database connections should sit in a
using statement so they close even when an exception is thrown.
A quick revision routine
Create a console app with dotnet new console and copy one section of the sheet into it each day, changing the values and predicting the output before you run it. The C# exercises cover the same topics if you want guided practice.
The C# lessons behind this cheat sheet