C# Cheat Sheet
Concept
A quick reference for daily work. The runnable program at the end uses most of these constructs together.
Data Types and Literals 42, 5_000_000_000L 32/64-bit signed double, float 3.14, 2.5f Binary floating point Money, exact decimal fractions bool, char
"text", $"{x}", @"C:\path", """raw""" int?, string? x ?? fallback, x?.Member (string Name, int Id) t = ("VCU", 1);
var (n, id) = t;, t == ("VCU", 1) compares element-wise Operators and Control Flow ??, ??=, ?., ! (null-forgiving) cond ? a: b if/else, switch statement switch (x) { case 1:...; break; }
x switch { < 10 => "small", _ => "large" } is null, is > 0 and < 10, { Speed: > 120 }, [_, 0x10, var s]
for, foreach, while, do/while, break, continue Methods, Classes, Interfaces, Generics Collections and LINQ Type / operator List<T> — Add, Remove, index
Dictionary<TKey, TValue> — TryGetValue FIFO / LIFO / priority
Queue<T>, Stack<T>, PriorityQueue<T, TPriority> ConcurrentDictionary, ConcurrentQueue, Channel<T> Filter / map / sort Where, Select, OrderBy/ThenBy Group / join / aggregate
GroupBy, Join, Sum, Average, Aggregate, CountBy Element / quantifier
First(OrDefault), Single, Any, All ToList, ToArray, ToDictionary, ToHashSet Exceptions, Async, Threading Files, JSON, HTTP DI, Configuration, Logging, Testing EF Core and ASP.NET Core dotnet new console -n App
Create a project (classlib, webapi, xunit, wpf, worker) dotnet run [file.cs]
Build and run (file-based apps in.NET 10) dotnet build -c Release / dotnet test / dotnet publish Build, test, publish dotnet add package X Add a NuGet package dotnet format Apply .editorconfig style
static int Add(int a, int b = 0) => a + b; // default parameter, expression body
void Parse(string s, out int value, ref int count, in Frame f) { ... }
public class Ecu(string code) : IDescribable { public string Code { get; } = code; }
public record Frame(uint Id, byte[] Data); // value equality, with-expressions
public interface IDescribable { string Describe(); }
static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;try { ... } catch (IOException ex) when (ex.HResult == 32) { ... } finally { ... }
throw; // rethrow, keeps stack trace
ArgumentNullException.ThrowIfNull(arg);
async Task<int> ReadAsync(CancellationToken ct = default) { await Task.Delay(10, ct); return 1; }
await Task.WhenAll(t1, t2); await Task.WhenAny(t1, t2); await task.WaitAsync(TimeSpan.FromSeconds(1));
lock (_gate) { ... } Interlocked.Increment(ref _n); Parallel.ForEach(items, x => ...);
var ch = Channel.CreateBounded<T>(100); await ch.Writer.WriteAsync(x); await foreach (var x in ch.Reader.ReadAllAsync()) { }string text = await File.ReadAllTextAsync(path); foreach (var line in File.ReadLines(path)) { }
await using var fs = File.OpenRead(path); using var writer = new StreamWriter(path);
string json = JsonSerializer.Serialize(obj); var obj2 = JsonSerializer.Deserialize<T>(json);
var data = await http.GetFromJsonAsync<T>("/api/items", ct); var r = await http.PostAsJsonAsync("/api/items", item, ct);services.AddSingleton<IClock, SystemClock>(); services.AddScoped<IRepo, Repo>(); services.AddTransient<Worker>();
services.AddOptions<BenchOptions>().BindConfiguration("Bench").ValidateDataAnnotations().ValidateOnStart();
logger.LogInformation("Flashing {Ecu} with {File}", ecu, file);
[Fact] public void Test() { Assert.Equal(expected, actual); } [Theory, InlineData(1, 2)] public void T(int a, int b) { }var items = await db.Ecus.Where(e => e.Active).Include(e => e.Dtcs).AsNoTracking().ToListAsync(ct);
db.Add(entity); await db.SaveChangesAsync(ct);
var app = WebApplication.CreateBuilder(args).Build();
app.MapGet("/ecus/{code}", (string code, Repo repo) => repo.Find(code) is { } e ? Results.Ok(e) : Results.NotFound());
app.Run();Why It Matters
A cheat sheet speeds up everyday work and is a compact revision sheet before interviews.
Example
66.1 The cheat sheet as one running program
#:property PublishAot=false
using System.Text.Json;
// ---- Types, operators, conditions, loops ----
int i = 42; long l = 5_000_000_000; double d = 3.14; decimal m = 19.99m; bool ok = true; char c = 'A'; string s = "text";
var inferred = new List<int> { 1, 2, 3 };
int? maybe = null; string display = maybe?.ToString() ?? "none";
string size = i switch { < 10 => "small", < 100 => "medium", _ => "large" };
for (int k = 0; k < 3; k++) { if (k == 1) continue; }
foreach (var x in inferred) { }
while (ok) { ok = false; }
Console.WriteLine($"types: {i} {l} {d} {m} {c} {s} {display} {size}");
// ---- Collections + LINQ ----
List<string> list = ["VCU", "BMS", "GW"];
Dictionary<string, int> dict = new() { ["VCU"] = 0x7E0 };
HashSet<int> set = [1, 2, 2, 3];
var q = list.Where(e => e.Length == 3).OrderBy(e => e).Select(e => e.ToLower()).ToList();
Console.WriteLine($"collections: {list.Count} {dict["VCU"]:X} {set.Count} linq: {string.Join(",", q)} any: {list.Any(e => e == "GW")} first: {list.First()}");
// ---- Methods, classes, interfaces, generics, records ----
var ecu = new Ecu("VCU") { Firmware = "2.4.1" };
IDescribable desc = ecu;
Console.WriteLine($"oop: {desc.Describe()} max: {Max(3, 9
…Expected Result
types: 42 5000000000 3.14 19.99 A text none medium
collections: 3 7E0 3 linq: bms,vcu any: True first: VCU
oop: VCU 2.4.1 max: 9 record: Point { X = 1, Y = 5 }
exceptions: bad state
async: 10,20
threading: 1001
json: Point { X = 3, Y = 4 }Common Mistakes
Copying snippets without the using directives or packages they need (e.g. System.Text.Json, Microsoft.EntityFrameworkCore).
Using the reflection-based JsonSerializer in a Native AOT app — it's disabled there (hence #:property PublishAot=false in the program above, or use source generation as in Module 28).
Best Practices
Keep your own cheat sheet with snippets from your projects.
Prefer the official docs (learn.microsoft.com) for API details.
Interview Relevance
Revision material for all interview levels.
Practice Questions
Add a section for pattern matching examples to your own cheat sheet.
Write the EF Core snippet as a complete program with a model and a SQLite database.
Add IAsyncEnumerable<T> and yield return examples.
Add the dotnet commands for creating and running an xUnit v3 test project.
Quick Quiz
Q1. (Multiple choice) Which type should represent money? A) double B) float C) decimal D) int Answer: C.
Q2. (Predict the output) new HashSet<int> { 1, 2, 2, 3 }.Count Answer: 3 (verified).
Q3. (True/False) record types compare by value.
Answer: True. Q4. (Find the bug) List<string> list = ["VCU"]; var first = list.Single(x => x.StartsWith("X"));
Answer: Single throws when there is no match (or more than one); use SingleOrDefault/FirstOrDefault when absence is possible.
Coding Challenge
Using only cheat-sheet constructs, read a list of (ecu, voltage) tuples, group by ECU, and print the ECUs whose average voltage is below 12.0 V, sorted by average.
(string Ecu, double Volts)[] readings = [("VCU", 12.6), ("BMS", 11.8), ("VCU", 12.4), ("BMS", 11.9), ("GW", 11.2)];
var low = readings.GroupBy(r => r.Ecu)
.Select(g => (Ecu: g.Key, Avg: g.Average(r => r.Volts)))
.Where(x => x.Avg < 12.0)
.OrderBy(x => x.Avg);
foreach (var (ecu, avg) in low) Console.WriteLine($"{ecu}: {avg:F2} V");