C#Printable

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.

Back to the C# tutorial

Basics

SyntaxWhat it doesLesson
Console.WriteLine("Hi");Print a lineIntroduction
int n = 5; var x = 2.5; const int Max = 10;Variables, inference, constantsVariables & Types
decimal price = 9.99m;Exact decimal for moneyVariables & Types
int.TryParse(text, out int n)Safe text-to-number conversionVariables & Types
7 / 2 7 % 2 7 / 2.0Integer division, remainder, decimal divisionOperators & Math
Math.Round(x, 2) Random.Shared.Next(1, 7)Rounding and random numbersOperators & Math

Strings & input

SyntaxWhat it doesLesson
$"Hi {name}, total {sum:F2}"Interpolation with formattingStrings
s.Trim() s.ToUpper() s.Contains("x")Common string methodsStrings
s.Split(',') string.Join(", ", items)Split and joinStrings
s[^1] s[1..4]Last character and rangesStrings
string? line = Console.ReadLine();Read a line of inputInput & Output
Console.ReadLine() ?? ""Default when input is nullInput & Output

Control flow & methods

SyntaxWhat it doesLesson
var s = ok ? "yes" : "no";Conditional operatorif & switch
x switch { < 0 => "neg", 0 => "zero", _ => "pos" }Switch expression with patternsif & switch
for (int i = 0; i < n; i++) foreach (var x in items)LoopsLoops
while (c) { } do { } while (c); break; continue;Condition loops and controlLoops
int Square(int x) => x * x;Expression-bodied methodMethods
void Log(string m, bool urgent = false) then Log("x", urgent: true)Optional and named argumentsMethods
(int Min, int Max) Range(...)Return a tupleMethods

Collections

SyntaxWhat it doesLesson
int[] a = { 1, 2, 3 }; a.LengthArrayArrays
Array.Sort(a) a[^1] a[1..3]Sort, last item, sliceArrays
var list = new List<string>(); list.Add("x"); list.CountListLists & Dictionaries
var d = new Dictionary<string, int>(); d["a"] = 1;DictionaryLists & Dictionaries
d.TryGetValue("a", out int v)Safe lookupLists & Dictionaries
new HashSet<int>() new Queue<T>() new Stack<T>()Set, queue and stackLists & Dictionaries

Types

SyntaxWhat it doesLesson
class Account { private decimal balance; public void Deposit(decimal a) { } }Class with encapsulated dataClasses & Objects
public string Name { get; init; } public decimal Total => P * Q;PropertiesProperties & Constructors
public Order(string c) { } class Order(string c) { }Constructor and primary constructorProperties & Constructors
class Dog : Animal virtual override abstractInheritanceInheritance & Polymorphism
interface INotifier { void Send(string m); }InterfaceInterfaces
record Product(string Name, decimal Price); p with { Price = 5 }Record and withStructs & Records
enum Status { Pending, Paid } [Flags]EnumEnums
try { } catch (IOException ex) { } finally { } throw;ExceptionsExceptions

Advanced C#

SyntaxWhat it doesLesson
T Max<T>(T a, T b) where T : IComparable<T>Generic method with constraintGenerics
items.Where(x => x > 0).Select(x => x * 2).ToList()LINQ pipelineLINQ
GroupBy OrderBy FirstOrDefault Any SumCommon LINQ methodsLINQ
Func<int, int> f = x => x * 2; Action<string> logDelegates and lambdasDelegates & Lambdas
public event EventHandler<T>? Changed; Changed?.Invoke(this, e)EventsDelegates & Lambdas
async Task<int> GetAsync() await Task.WhenAll(a, b)async/awaitasync & await
File.ReadAllText(p) Path.Combine(a, b)Files and pathsFiles & JSON
JsonSerializer.Serialize(obj) Deserialize<T>(json)JSONFiles & JSON
x?.Name ?? "none" obj is { Total: > 100 }Null operators and patternsNullable & Patterns
[Fact] [Theory] Assert.Equal(expected, actual)xUnit testsUnit Testing
app.MapGet("/items/{id:int}", (int id) => ...)Minimal API endpointMinimal 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