📋 Cheat Sheets

C# Cheat Sheet — Syntax, LINQ, Async, and Common Patterns


Click any item to expand the explanation and examples.

📝 Basics

Variables and types basics
int age = 30;
double price = 9.99;
string name = "Alice";
bool active = true;
var items = new List<string>();  // type inferred

// Constants
const int MaxRetries = 3;

// Nullable types
int? maybeNull = null;
string? maybeName = null;
String interpolation and formatting basics
string name = "World";
Console.WriteLine($"Hello, {name}!");
Console.WriteLine($"Price: {9.99:C}");       // $9.99
Console.WriteLine($"Date: {DateTime.Now:d}"); // 3/15/2026

// Raw string literals (C# 11)
string json = """
    {
        "name": "Alice",
        "age": 30
    }
    """;
Control flow basics
// Pattern matching switch
string result = status switch
{
    "active" => "Running",
    "paused" => "On hold",
    _ => "Unknown"
};

// If / else
if (age >= 18) { /* ... */ }
else if (age >= 13) { /* ... */ }
else { /* ... */ }

// Ternary
string label = age >= 18 ? "adult" : "minor";

📦 Collections

List, Dictionary, HashSet collections
// List
var names = new List<string> { "Alice", "Bob" };
names.Add("Charlie");
names.Remove("Bob");
bool has = names.Contains("Alice");

// Dictionary
var ages = new Dictionary<string, int>
{
    ["Alice"] = 30,
    ["Bob"] = 25
};
ages["Charlie"] = 35;
ages.TryGetValue("Alice", out int age);

// HashSet
var tags = new HashSet<string> { "a", "b" };
tags.Add("c");
tags.UnionWith(new[] { "d", "e" });
Arrays and spans collections
int[] nums = { 1, 2, 3, 4, 5 };
int[] slice = nums[1..3];  // { 2, 3 }
int last = nums[^1];       // 5

// Span (stack-allocated view, no copy)
Span<int> span = nums.AsSpan(1, 3);

🔍 LINQ

Filtering, mapping, aggregating linq
var numbers = new[] { 1, 2, 3, 4, 5, 6 };

var evens = numbers.Where(n => n % 2 == 0);
var doubled = numbers.Select(n => n * 2);
var sum = numbers.Sum();
var first = numbers.First(n => n > 3);  // 4
var any = numbers.Any(n => n > 10);     // false

// Chaining
var result = numbers
    .Where(n => n > 2)
    .Select(n => n * 10)
    .OrderByDescending(n => n)
    .ToList();
GroupBy, Join, Distinct linq
var people = new[]
{
    new { Name = "Alice", Dept = "Eng" },
    new { Name = "Bob", Dept = "Eng" },
    new { Name = "Charlie", Dept = "Sales" },
};

// Group
var groups = people.GroupBy(p => p.Dept);
foreach (var g in groups)
    Console.WriteLine($"{g.Key}: {g.Count()}");

// Distinct
var unique = names.Distinct().ToList();

// ToDictionary
var dict = people.ToDictionary(p => p.Name, p => p.Dept);

⚡ Async / Await

Async methods and Task async
async Task<string> FetchDataAsync(string url)
{
    using var client = new HttpClient();
    return await client.GetStringAsync(url);
}

// Parallel async
var tasks = urls.Select(url => FetchDataAsync(url));
string[] results = await Task.WhenAll(tasks);

// Async streams
async IAsyncEnumerable<int> GenerateAsync()
{
    for (int i = 0; i < 10; i++)
    {
        await Task.Delay(100);
        yield return i;
    }
}

🏗️ OOP and Records

Classes, interfaces, records oop
// Record (immutable data class)
public record User(string Name, string Email);
var user = new User("Alice", "alice@example.com");
var updated = user with { Email = "new@example.com" };

// Interface
public interface IRepository<T>
{
    Task<T?> GetByIdAsync(int id);
    Task<IEnumerable<T>> GetAllAsync();
}

// Class with primary constructor (C# 12)
public class UserService(IRepository<User> repo)
{
    public Task<User?> GetUser(int id) => repo.GetByIdAsync(id);
}
Pattern matching oop
string Describe(object obj) => obj switch
{
    int n when n > 0 => "positive int",
    string { Length: > 10 } => "long string",
    null => "null",
    _ => "something else"
};

// List patterns (C# 11)
int[] arr = { 1, 2, 3 };
if (arr is [1, _, 3])
    Console.WriteLine("Starts with 1, ends with 3");

🛠️ Common Patterns

Dependency injection (ASP.NET) aspnet
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddDbContext<AppDbContext>();

var app = builder.Build();
app.MapGet("/users", async (IUserService svc) =>
    await svc.GetAllAsync());
app.Run();
Minimal API endpoints aspnet
app.MapGet("/items", () => db.Items.ToListAsync());
app.MapGet("/items/{id}", async (int id) =>
    await db.Items.FindAsync(id) is Item item
        ? Results.Ok(item)
        : Results.NotFound());
app.MapPost("/items", async (Item item) =>
{
    db.Items.Add(item);
    await db.SaveChangesAsync();
    return Results.Created($"/items/{item.Id}", item);
});
Null handling basics
// Null-conditional
int? length = name?.Length;

// Null-coalescing
string display = name ?? "Unknown";

// Null-coalescing assignment
name ??= "Default";

// Null-forgiving (suppress warning)
string definitelyNotNull = maybeNull!;