Cheatsheet
C# cheatsheet: syntax, LINQ, async, records, pattern matching, nullable refs. The one-page reference.
C# — cheatsheet
EXAMPLE
// ===== Variables =====
int i = 42;
long l = 4_000_000_000L;
double d = 3.14;
decimal m = 49.95m; // money
bool b = true;
char c = 'A';
string s = "Alex";
string? maybe = null; // nullable reference type
var inferred = new List<int>();
// ===== Control flow =====
if (cond) { } else if (cond2) { } else { }
for (int n = 0; n < 10; n++) { }
foreach (var x in xs) { }
while (cond) { }
do { } while (cond);
// Switch expression
var size = n switch {
< 10 => "small",
< 100 => "medium",
_ => "large",
};
// ===== Records =====
public record User(int Id, string Name, string Email);
public record class UserEntity(int Id) { public string? Note { get; init; } }
public record struct Point(int X, int Y);
var u = new User(1, "Alex", "a@x.io");
var u2 = u with { Name = "Sam" };
// ===== Pattern matching =====
string Describe(object o) => o switch {
null => "nothing",
int n when n < 0 => "negative",
int n => "int " + n,
string s => "str " + s,
User { Name: var n } => n,
_ => "other",
};
// ===== Async =====
public async Task<string> GetTitleAsync(string url) {
using var http = new HttpClient();
return await http.GetStringAsync(url);
}
// Parallel
await Parallel.ForEachAsync(ids, async (id, ct) => { /* ... */ });
// Cancellation
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var data = await http.GetStringAsync(url, cts.Token);
// ===== LINQ =====
using System.Linq;
var evens = nums.Where(n => n % 2 == 0).Select(n => n * n).ToList();
var sum = nums.Sum();
var first = users.FirstOrDefault(u => u.Id == 1);
var byTag = users.GroupBy(u => u.Tag).ToDictionary(g => g.Key, g => g.Count());
var sorted = users.OrderBy(u => u.Name).ThenByDescending(u => u.Id).ToList();
// ===== Collections =====
var list = new List<int> { 1, 2, 3 };
var dict = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 };
var set = new HashSet<string> { "vip" };
var queue = new Queue<string>(); // Enqueue / Dequeue
var stack = new Stack<string>(); // Push / Pop
// ===== Generics =====
public static T First<T>(IEnumerable<T> xs) => xs.First();
public static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;
// ===== Exceptions =====
try {
Risky();
} catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) {
/* not found */
} catch (Exception ex) {
Console.Error.WriteLine(ex);
throw;
} finally {
Cleanup();
}
// ===== using / IDisposable =====
using var stream = File.OpenRead("a.txt");
// Disposed at scope exit
// using declarations (C# 8+)
await using var conn = await db.OpenConnectionAsync();
// ===== File IO =====
var text = await File.ReadAllTextAsync("a.txt");
var lines = File.ReadAllLines("a.txt");
await File.WriteAllTextAsync("b.txt", text);
// ===== HTTP =====
using var http = new HttpClient();
var r = await http.GetAsync(url);
if (r.IsSuccessStatusCode) {
var s = await r.Content.ReadAsStringAsync();
}
// JSON
using System.Text.Json;
var user = JsonSerializer.Deserialize<User>(json);
var json2 = JsonSerializer.Serialize(user);
// ===== Tuples =====
(string Name, int Age) p = ("Alex", 30);
var (n, a) = p;
// ===== Patterns =====
// - record over class for DTOs
// - var for clear inference
// - LINQ + Where/Select/GroupBy chains
// - async / await all the way down
// - using for IDisposable / IAsyncDisposable
// ===== Pitfalls =====
// - decimal vs double for money
// - .Result on Task -> deadlocks
// - LINQ ToList in hot loops
// - Catching Exception broadly
Why it matters
C# cheatsheet covers the daily 80%: records + pattern matching + LINQ + async + nullable refs + collections + IDisposable. Pin it during a project; the syntax is dense but stable.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…