C#C# · Lesson 9 of 9
C# Cheatsheet
Modern C# on one page — records, LINQ, async, pattern matching.
C#
// ── Basics (top-level statements) ───────
int x = 42;
double pi = 3.14;
string name = "Ada";
var list = new List<string>(); // inference
Console.WriteLine($"{name} is {x}"); // interpolation
// ── Control flow ────────────────────────
if (x > 10) { } else if (x > 5) { } else { }
for (int i = 0; i < 5; i++) { }
foreach (var item in items) { }
while (cond) { }
var label = x > 10 ? "big" : "small";
value ?? fallback; obj?.Prop; // null tools
// switch expression + patterns:
string Describe(object o) => o switch {
int n when n > 100 => "big number",
int n => $"number {n}",
string s => $"text {s.Length} long",
null => "nothing",
_ => "unknown",
};
// ── Records & classes ───────────────────
record Point(int X, int Y); // value equality free
var p2 = p1 with { Y = 5 }; // non-destructive update
class Dog {
public string Name { get; init; } // properties
public int Age { get; private set; }
public string Bark() => $"{Name} woofs"; // expression body
}C#
// ── Collections ─────────────────────────
var nums = new List<int> { 3, 1, 4 };
nums.Add(1); nums[0]; nums.Count; nums.Contains(4);
var ages = new Dictionary<string, int> { ["Ada"] = 17 };
ages.TryGetValue("Eve", out var age);
int[] arr = [1, 2, 3]; // collection expression
// ── LINQ — the crown jewel ──────────────
var honorRoll = students
.Where(s => s.Grade >= 90)
.OrderBy(s => s.Name)
.Select(s => s.Name)
.ToList();
var total = nums.Sum();
var best = students.MaxBy(s => s.Grade);
var byAge = students.GroupBy(s => s.Age);
var any = students.Any(s => s.Grade == 100);
// ── Async ───────────────────────────────
async Task<string> FetchAsync(string url) {
using var http = new HttpClient();
return await http.GetStringAsync(url);
}
var results = await Task.WhenAll(a, b); // concurrent
// ── Exceptions ──────────────────────────
try { Risky(); }
catch (IOException e) { Handle(e); }
finally { Cleanup(); }
// dotnet new console | dotnet run | dotnet test
// dotnet add package Newtonsoft.Json