Language :: C#

C# Handbook

C# is a statically typed language for .NET. You can use it to write console tools, web APIs, desktop apps, and games. The console examples use the same .NET commands on Windows, macOS, and Linux.

Pick C# when

  • Your web application uses ASP.NET Core and you want the same language for endpoints, domain models, and tests.
  • You are writing Unity gameplay scripts or extending an existing .NET application.

Think twice before choosing C# when

  • Your deployment has tight startup or memory budgets. Measure the published application on the target device before committing to a deployment model.
  • Your project depends on a library or engine tied to another runtime. Check whether the integration justifies adding a second runtime.

C# vs. its closest alternatives

  • Java fits teams with JVM libraries and deployment tooling. C# fits teams building on .NET and offers LINQ for querying collections.
  • Go offers goroutines and channels for concurrent services. C# uses tasks and async methods for asynchronous I/O and offers records and pattern matching for domain models.
  • Python fits workflows built around Python data and scripting libraries. C# checks declared and inferred types at compile time, which helps when changing shared interfaces.

Resources

Topics

Getting Started

Install the .NET 10 SDK and check that a 10.0 SDK appears in the list. The project targets .NET 10, which defaults to C# 14.

bash
dotnet --list-sdks
dotnet new console -n HandbookDemo --framework net10.0
cd HandbookDemo

Replace Program.cs with this program. The using directive brings Console into scope. The compiler creates the entry point for the top-level statement.

csharp
using System;

Console.WriteLine("Hello, C#!");
bash
dotnet run

The program prints Hello, C#!. Each standalone console example below can replace Program.cs in the same project.

Variables & Types

Built-in Types and Literals

Use int for whole numbers, double for floating-point measurements, decimal for amounts that need decimal precision, bool for truth values, and char for a single UTF-16 code unit. A real literal such as 1.5 is a double by default. The m suffix makes 2.50 a decimal.

csharp
using System;

int quantity = 4;
double distance = 1.5;
decimal price = 2.50m;
bool inStock = quantity > 0;
char grade = 'A';

Console.WriteLine(price * quantity == 10m); // True
Console.WriteLine(distance > 1 && inStock); // True
Console.WriteLine(grade); // A

Type Inference and Reassignment

The initializer makes count an int. Assigning another int works. Assigning text produces a compiler error. Use an explicit type when the initializer leaves the intended type unclear.

csharp
using System;

var count = 2;
count = 5;
// count = "five"; // Cannot assign a string to an int.
Console.WriteLine(count); // 5

Constants and Readonly Fields

A const needs a value known at compile time. A readonly instance field can receive a different value in each constructor call. After construction the field cannot be reassigned.

csharp
using System;

Console.WriteLine(new Cart(3).TotalInCents); // 750

sealed class Cart
{
    private const int UnitPriceInCents = 250;
    private readonly int quantity;

    public Cart(int quantity) => this.quantity = quantity;

    public int TotalInCents => quantity * UnitPriceInCents;
}

Value and Reference Semantics

Assigning an int copies its value. Assigning an array copies the reference, so both variables still refer to the same array. Changing an element through either variable is visible through the other.

csharp
using System;

int original = 3;
int copy = original;
copy = 8;
Console.WriteLine(original); // 3
Console.WriteLine(copy); // 8

int[] scores = [3];
int[] alias = scores;
alias[0] = 8;
Console.WriteLine(scores[0]); // 8

Nullable Values and Fallbacks

An int? can hold an int or null. The ?? operator uses its right operand when its left operand is null. The default console template also enables nullable reference analysis, which lets string? express that a text reference may be null.

csharp
using System;

int? score = null;
string? nickname = null;

Console.WriteLine(score ?? 0); // 0
Console.WriteLine(nickname ?? "Guest"); // Guest

score = 8;
Console.WriteLine(score ?? 0); // 8

Strings

Double quotes delimit a string. The dollar sign enables interpolation, so the expression inside braces supplies part of the result. Single quotes delimit a char such as A.

csharp
using System;

string name = "Alice";
string message = $"Hello, {name}!";
Console.WriteLine(message); // Hello, Alice!

Immutability and Reassignment

Strings are immutable. Trim and Replace return a string with the requested changes. Ignoring the return value leaves the variable as it was. Reassignment makes the variable refer to the result, while any other reference still sees the original text.

csharp
using System;

string label = "  green tea  ";
string original = label;
label.Trim();
Console.WriteLine($"[{label}]"); // [  green tea  ]

label = label.Trim().Replace("green", "mint");
Console.WriteLine($"[{label}]"); // [mint tea]
Console.WriteLine($"[{original}]"); // [  green tea  ]

Searching and Slicing

Contains answers whether text is present. IndexOf returns the zero-based start position, or -1 when there is no match. Check that result before slicing. The range starts after the colon and continues to the end. Ordinal comparison is appropriate for a fixed marker in a data format.

csharp
using System;

string entry = "drink: mint tea";
Console.WriteLine(entry.Contains("tea", StringComparison.Ordinal)); // True
int separator = entry.IndexOf(':');
string value = separator >= 0 ? entry[(separator + 1)..].Trim() : entry;
Console.WriteLine(value); // mint tea

Splitting and Joining

Split returns an array of substrings. TrimEntries removes surrounding whitespace and RemoveEmptyEntries drops empty fields. Join inserts a separator between the remaining values.

csharp
using System;

string input = " mint, , lemon, ginger ";
string[] flavors = input.Split(',',
    StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(string.Join(" / ", flavors)); // mint / lemon / ginger

Building Text in a Loop

StringBuilder is a mutable buffer. Append adds text to the buffer and ToString returns an immutable string snapshot. Use a builder when assembling text through repeated appends. Interpolation keeps a single short expression readable.

csharp
using System;
using System.Text;

var builder = new StringBuilder();
foreach (string item in new[] { "mint", "lemon" })
{
    builder.Append('[').Append(item).Append(']');
}
Console.WriteLine(builder.ToString()); // [mint][lemon]

Control Flow

The if branch runs when the comparison is true. At 72 the program prints Pass. Change the score to 59 and it prints Try again.

csharp
using System;

int score = 72;
if (score >= 60)
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Try again");
}

Selecting a Value with switch

A switch expression checks its arms in order and returns the first matching result. The discard pattern _ handles any value that reaches the last arm. A conditional expression uses one Boolean test to choose between two values.

csharp
using System;

int score = 85;
string band = score switch
{
    >= 90 => "Excellent",
    >= 60 => "Pass",
    _ => "Try again"
};
string parity = score % 2 == 0 ? "even" : "odd";
Console.WriteLine($"{band}, {parity}"); // Pass, odd

Iterating over an Array

An array has a fixed length. The foreach loop assigns the next element to score on each iteration and prints 72, 85, and 91 on separate lines.

csharp
using System;

int[] scores = [72, 85, 91];
foreach (int score in scores)
{
    Console.WriteLine(score);
}

Indexing and Loop Conditions

A for loop lets you use the index explicitly, and the condition stops it before the index reaches Length. A while loop repeats while its condition is true. Update the state in the body so the loop can finish.

csharp
using System;

int[] scores = [72, 85];
for (int index = 0; index < scores.Length; index++)
{
    Console.WriteLine($"{index}: {scores[index]}");
}

int remaining = 2;
while (remaining > 0)
{
    Console.WriteLine(remaining);
    remaining--;
}

Methods & Functions

The parameters left and right receive the arguments 3 and 4. The int before Add is the return type, and the arrow returns the value of the expression.

csharp
using System;

Console.WriteLine(Add(3, 4)); // 7

static int Add(int left, int right) => left + right;

Named, Optional, and Variable Arguments

An optional parameter supplies a default when the caller omits it. A named argument identifies the parameter it supplies. A params array lets a caller pass several values as individual arguments.

csharp
using System;

Console.WriteLine(Greet("Ada")); // Hello, Ada!
Console.WriteLine(Greet(name: "Ada", greeting: "Hi")); // Hi, Ada!
Console.WriteLine(Sum(2, 3, 4)); // 9

static string Greet(string name, string greeting = "Hello") => $"{greeting}, {name}!";

static int Sum(params int[] values)
{
    int total = 0;
    foreach (int value in values)
    {
        total += value;
    }
    return total;
}

Passing Behavior with a Lambda

Func describes a callable value. Func with two type arguments takes an input of the first type and returns the second type. The lambda supplies the operation to perform when the delegate is called.

csharp
using System;

Func<int, int> square = value => value * value;
Console.WriteLine(square(4)); // 16

Parsing Input

TryParse returns true when the text represents an int and writes the result through the out parameter. Try replacing 42 with hello. The branch is skipped because conversion fails.

Parse a valid integer

csharp
using System;

string input = "42";
if (int.TryParse(input, out int value))
{
    Console.WriteLine(value + 1); // 43
}

TryParse returns true for 42, so the addition prints 43.

Handle an invalid integer

csharp
using System;

string input = "42kg";
if (!int.TryParse(input, out _))
{
    Console.WriteLine("Invalid integer");
}

The entire input must be valid. The suffix makes TryParse return false and the program prints Invalid integer.

Growing a List

A List<string> grows as you add names. Index 0 selects the first element, and Count reports the number of elements currently in the list.

Append and index list elements

csharp
using System;
using System.Collections.Generic;

var names = new List<string> { "Ada", "Grace" };
names.Add("Lin");
Console.WriteLine(names[0]); // Ada
Console.WriteLine(names.Count); // 3

After Add, the first name is still Ada and Count is 3.

Remove an item and inspect the result

csharp
using System;
using System.Collections.Generic;

var names = new List<string> { "Ada", "Grace", "Lin" };
Console.WriteLine(names.Remove("Grace")); // True
Console.WriteLine(string.Join(", ", names)); // Ada, Lin

Remove returns true for the first match. The other names keep their relative order.

Writing and Reading a File

Run this in the practice project directory. WriteAllLines creates or replaces names.txt there. ReadLines reads one line at a time, and the loop prints Ada followed by Grace.

Write and read text lines

csharp
using System;
using System.IO;

File.WriteAllLines("names.txt", ["Ada", "Grace"]);
foreach (string name in File.ReadLines("names.txt"))
{
    Console.WriteLine(name);
}

WriteAllLines creates the file and ReadLines enumerates its lines in order.

Append without replacing existing lines

csharp
using System;
using System.IO;

string path = Path.GetTempFileName();
try
{
    File.WriteAllLines(path, ["Ada"]);
    File.AppendAllLines(path, ["Lin"]);
    foreach (string name in File.ReadLines(path))
    {
        Console.WriteLine(name);
    }
}
finally
{
    File.Delete(path);
}

AppendAllLines adds a line to the existing file. This example prints Ada followed by Lin and removes its temporary file.

Adding a NuGet Package

Run these commands in the console project. The first adds a Humanizer package reference to the project file and restores it from NuGet. The second lists the resolved version.

bash
dotnet package add Humanizer
dotnet list package

Replace Program.cs with this example and run dotnet run. ToQuantity comes from the Humanizer package.

csharp
using System;
using Humanizer;

Console.WriteLine("person".ToQuantity(2)); // 2 people

Writing a Unit Test

From the parent directory of HandbookDemo, create a separate xUnit project. The template restores its test dependencies from NuGet.

bash
dotnet new xunit -n HandbookTests --framework net10.0
cd HandbookTests

Replace UnitTest1.cs with this example. Fact marks a test for xUnit to discover. Assert.Equal compares the expected result with the method result. Run the test and expect one pass.

csharp
using Xunit;

public class AdditionTests
{
    [Fact]
    public void AddsTwoNumbers()
    {
        Assert.Equal(7, Add(3, 4));
    }

    private static int Add(int left, int right) => left + right;
}
bash
dotnet test

The examples that follow are reference fragments. Read each one in the context described by its heading and notes.

Classes & OOP

Classes bundle state and behavior around invariants. Expose operations that preserve valid state instead of permitting arbitrary field changes.

Override inherited behavior

csharp
using System;

Animal pet = new Dog("Rex", "Labrador");
Console.WriteLine(pet.Speak()); // Rex says Woof!

public class Animal {
    public string Name { get; init; }   // init-only property (C# 9)
    public string Sound { get; private set; }

    public Animal(string name, string sound) {
        Name = name;
        Sound = sound;
    }

    public virtual string Speak() => $"{Name} says {Sound}";

    public override string ToString() => $"Animal({Name})";
}

public class Dog : Animal {
    public string Breed { get; }

    public Dog(string name, string breed)
        : base(name, "Woof") {
        Breed = breed;
    }

    public override string Speak() => base.Speak() + "!";
}

A Dog can be used through an Animal reference. The virtual call still selects Dog.Speak.

Require an implementation in derived classes

csharp
using System;

Shape shape = new Rectangle(3, 4);
Console.WriteLine(shape.Area()); // 12

// Abstract class
public abstract class Shape {
    public abstract double Area();
    public string Describe() => $"Shape with area {Area():F2}";
}

public sealed class Rectangle(double width, double height) : Shape {
    public override double Area() => width * height;
}

// Struct (value type — copied by value)
public struct Point {
    public double X { get; }
    public double Y { get; }
    public Point(double x, double y) { X = x; Y = y; }
    public double Distance() => Math.Sqrt(X * X + Y * Y);
}

Shape defines shared description logic and leaves Area to each concrete shape.

Interfaces & Generics

Interfaces describe capabilities independently of implementations. Generics preserve type relationships in reusable containers and operations.

Define a repository contract

csharp
// Generic interface with constraints
public interface IRepository<T> where T : class {
    Task<T?> FindByIdAsync(int id);
    Task<IEnumerable<T>> FindAllAsync();
    Task SaveAsync(T entity);
    Task DeleteAsync(int id);
}

The constraint requires a reference type. The nullable lookup result represents a missing entity.

Convert between enum names and values

csharp
using System;

// Enum
Status s = Status.Active;
int val = (int)s;             // 1
string name2 = s.ToString();  // 'Active'
Console.WriteLine(val); // 1
Console.WriteLine(name2); // Active
if (Enum.TryParse("Pending", out Status parsed)) Console.WriteLine(parsed);

public enum Status { Pending, Active, Inactive }

Active has numeric value 1. TryParse can convert the name Pending to its enum value.

LINQ

LINQ (Language Integrated Query) lets you filter, transform, and summarize sequences. These examples use LINQ to Objects. To run any example, replace Program.cs in the console project from Getting Started and run dotnet run.

Filtering with Where

Where calls the predicate for each element and keeps the elements for which it returns true. In n => n % 2 == 0, n is the current element.

csharp
using System;
using System.Linq;

var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var evens = numbers.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); // 2, 4, 6

Transforming with Select

Select produces one result per input element. Here it extracts a name from each record. You can also project into a different type, such as the length of each name.

csharp
using System;
using System.Linq;

var people = new[] { (Name: "Ada", Age: 36), (Name: "Grace", Age: 85) };
var names = people.Select(person => person.Name);
var lengths = names.Select(name => name.Length);
Console.WriteLine(string.Join(", ", names)); // Ada, Grace
Console.WriteLine(string.Join(", ", lengths)); // 3, 5

Sorting with two keys

OrderByDescending puts the highest scores first. ThenBy sorts equal scores by name. A second OrderBy would make the name the primary sort key.

csharp
using System;
using System.Linq;

var players = new[] { (Name: "Bo", Score: 10), (Name: "Ada", Score: 10),
                      (Name: "Cal", Score: 15) };
var ranked = players.OrderByDescending(player => player.Score)
                    .ThenBy(player => player.Name, StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", ranked.Select(player => player.Name)));
// Cal, Ada, Bo

Method syntax and query syntax

Both queries filter for even numbers, sort them from highest to lowest, and square them. The query clauses where, orderby, and select correspond to the method calls below. ToArray works with either form.

csharp
using System;
using System.Linq;

var numbers = Enumerable.Range(1, 10);
var methods = numbers.Where(n => n % 2 == 0)
                     .OrderByDescending(n => n)
                     .Select(n => n * n);
var query = from n in numbers
            where n % 2 == 0
            orderby n descending
            select n * n;

Console.WriteLine(string.Join(", ", methods.ToArray())); // 100, 64, 36, 16, 4
Console.WriteLine(string.Join(", ", query.ToArray()));   // 100, 64, 36, 16, 4

Deferred execution and snapshots

Where saves the filtering rule. Each enumeration runs it again, so a later pass can see new elements. ToList and ToArray enumerate immediately and store the results. For reference types, the snapshot stores references to the same objects.

csharp
using System;
using System.Linq;
using System.Collections.Generic;

var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n % 2 == 0);
var snapshot = query.ToList();

Console.WriteLine(string.Join(", ", query));    // 2
numbers.Add(4);
Console.WriteLine(string.Join(", ", query));    // 2, 4
Console.WriteLine(string.Join(", ", snapshot)); // 2

Finding the first match

First returns the first match and throws InvalidOperationException if there is none. FirstOrDefault returns the default value instead. For int, zero can be a real match, so the example also shows how to use nullable integers when you need to distinguish absence from zero.

csharp
using System;
using System.Linq;

var numbers = new[] { 0, 2, 4, 6 };

Console.WriteLine(numbers.First(n => n > 3));              // 4
Console.WriteLine(numbers.FirstOrDefault(n => n > 100));   // 0

int? match = numbers.Where(n => n > 100)
                    .Select(n => (int?)n)
                    .FirstOrDefault();
Console.WriteLine(match?.ToString() ?? "No match");        // No match

Checking conditions with Any and All

Any checks whether at least one element matches. All checks whether every element matches. Both can stop as soon as the answer is known. For an empty sequence, Any is false and All is true because no element violates the condition.

csharp
using System;
using System.Linq;

var numbers = new[] { 2, 4, 6 };
Console.WriteLine(numbers.Any(n => n > 5));       // True
Console.WriteLine(numbers.All(n => n % 2 == 0));  // True

var empty = Array.Empty<int>();
Console.WriteLine(empty.Any());                  // False
Console.WriteLine(empty.All(n => n > 0));        // True

Summarizing numbers

Sum adds the values. Average computes the arithmetic mean. Min and Max return the extremes. Count with a predicate counts only matches. For an empty sequence of int values, Sum and Count return zero, while Average, Min, and Max throw InvalidOperationException.

csharp
using System;
using System.Linq;
using System.Globalization;

var numbers = Enumerable.Range(1, 10);
Console.WriteLine(numbers.Sum());                           // 55
Console.WriteLine(numbers.Average().ToString(CultureInfo.InvariantCulture)); // 5.5
Console.WriteLine(numbers.Min());                           // 1
Console.WriteLine(numbers.Max());                           // 10
Console.WriteLine(numbers.Count(n => n > 5));               // 5

Grouping elements by a key

GroupBy computes a key for every element. Each group exposes its Key and can be enumerated to read the original elements that share it. Here the key is the parity of each number.

csharp
using System;
using System.Linq;

var numbers = Enumerable.Range(1, 6);
var groups = numbers.GroupBy(n => n % 2 == 0 ? "even" : "odd");

foreach (var group in groups)
{
    Console.WriteLine($"{group.Key}: {string.Join(", ", group)}");
}
// odd: 1, 3, 5
// even: 2, 4, 6

Putting it together in an order report

This report includes only paid orders. GroupBy collects them by customer, then Select builds one summary per customer. Sorting the summaries puts the largest total first. The amounts are whole euros to keep the arithmetic visible.

csharp
using System;
using System.Linq;

var orders = new[]
{
    (Customer: "Ada", Amount: 40, Paid: true),
    (Customer: "Bo", Amount: 75, Paid: true),
    (Customer: "Ada", Amount: 50, Paid: true),
    (Customer: "Bo", Amount: 100, Paid: false)
};

var report = orders.Where(order => order.Paid)
                   .GroupBy(order => order.Customer)
                   .Select(group => new
                   {
                       Customer = group.Key,
                       Orders = group.Count(),
                       Total = group.Sum(order => order.Amount)
                   })
                   .OrderByDescending(row => row.Total);

foreach (var row in report)
{
    Console.WriteLine($"{row.Customer}: {row.Orders} / {row.Total} EUR");
}
// Ada: 2 / 90 EUR
// Bo: 1 / 75 EUR

Async / Await

Run each example separately in the starter console project.

An async method can suspend at an incomplete await and resume on completion. A Task represents completion; async does not automatically move work to a background thread.

Await continues immediately for a completed task. For an incomplete task, the method suspends and resumes after completion; no dedicated thread is implied.
flowchart TD
    Call["Start async method"] --> Work["Run to await"]
    Work --> Check{"Task complete?"}
    Check -->|yes| Resume["Observe result or exception"]
    Check -->|no| Suspend["Suspend method"]
    Suspend -->|task completes| Resume
    Resume --> Continue["Continue or propagate failure"]

Awaiting a result

csharp
var pending = ReadAsync();
Console.WriteLine("Waiting");
Console.WriteLine(await pending);

static async Task<string> ReadAsync()
{
    await Task.Delay(50);
    return "Ready";
}

Waiting prints before Ready. The caller holds the task until it needs the result. For HTTP, await GetAsync, check the response status, read the body, and dispose the response. Reuse the HttpClient across calls.

Coordinating independent tasks

csharp
Task<string>[] tasks = [LoadAsync("A"), LoadAsync("B")];
var first = await Task.WhenAny(tasks);
Console.WriteLine($"First: {await first}");
Console.WriteLine(string.Join(", ", await Task.WhenAll(tasks)));

static async Task<string> LoadAsync(string name)
{
    await Task.Delay(20);
    return name;
}

WhenAny returns the first completed task. Await that task to observe its result or exception. WhenAll prints A, B in input order. Keeping the task objects lets both calls observe the same operations.

Cancelling an operation

csharp
using var cancellation = new CancellationTokenSource();
Task work = ProcessAsync(cancellation.Token);
cancellation.Cancel();

try
{
    await work;
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
    Console.WriteLine("Cancelled");
}

static async Task ProcessAsync(CancellationToken token)
{
    for (int i = 0; i < 3; i++)
    {
        token.ThrowIfCancellationRequested();
        await Task.Delay(100, token);
    }
}

The caller prints Cancelled. The delay observes the token while waiting. ThrowIfCancellationRequested adds a checkpoint between units of work.

For a method that yields values over time, see async streams.

Records & Pattern Matching

Run each example separately in the starter console project.

Records provide data-oriented syntax and value-based equality. Pattern matching inspects shapes, but record properties may still refer to mutable objects.

Comparing and copying records

csharp
var alice = new Person("Alice", 30);
var older = alice with { Age = 31 };
Console.WriteLine(alice == new Person("Alice", 30));
Console.WriteLine(alice == older);
Console.WriteLine(alice);

record Person(string Name, int Age);

The comparisons print True and False. The generated display still shows Age equal to 30 for alice. A with expression copies properties shallowly, so the two records can share objects referenced by their properties.

Copying a record struct

csharp
var freezing = new Temperature(0);
var warmer = freezing;
warmer.Celsius = 10;
Console.WriteLine(freezing.Fahrenheit);
Console.WriteLine(warmer.Fahrenheit);

record struct Temperature(double Celsius)
{
    public double Fahrenheit => Celsius * 9 / 5 + 32;
}

The lines print 32 and 50 because assignment copied the struct. The positional property is writable. Declare the record struct readonly for an init-only positional property.

Matching types, properties, and lists

csharp
Console.WriteLine(Describe(-2));
Console.WriteLine(Describe(""));
Console.WriteLine(new Point(3, 4) is { X: > 0, Y: > 0 });
int[] values = [1, 2, 3];
Console.WriteLine(values is [1, 2, ..]);

static string Describe(object? value) => value switch
{
    int number when number < 0 => "negative",
    int number => $"integer {number}",
    string { Length: 0 } => "empty",
    string text => text,
    null => "missing",
    _ => "other"
};

record Point(double X, double Y);

The lines are negative, empty, True, and True. Put guarded cases before broader cases that would also match. The coordinate pattern checks both properties. The list pattern accepts any tail after the first two elements.

Exceptions

Run each example separately in the starter console project.

Catch specific failures where recovery or useful context is possible. Use disposal constructs to release resources on both success and failure.

Catching a recoverable failure

csharp
Console.WriteLine(Divide(0));

static string Divide(int divisor)
{
    try
    {
        return (10 / divisor).ToString();
    }
    catch (DivideByZeroException)
    {
        return "Invalid divisor";
    }
    finally
    {
        Console.WriteLine("Finished attempt");
    }
}

Finished attempt prints before Invalid divisor because finally runs as control leaves the method. Try a divisor of 2 to see the same cleanup message before 5.

Filtering and rethrowing exceptions

csharp
try
{
    throw new AppException("Quota exceeded", 429);
}
catch (AppException error) when (error.Code == 429)
{
    Console.WriteLine("Try again later");
}
catch (AppException)
{
    Console.WriteLine("Unexpected application error");
    throw;
}

sealed class AppException(string message, int code) : Exception(message)
{
    public int Code { get; } = code;
}

Code 429 prints Try again later. Change it to 500 to reach the second handler. The bare throw preserves the original stack trace.

Disposing resources at scope exit

csharp
Console.WriteLine(ReadFirstLine());

static string? ReadFirstLine()
{
    using var stream = new MemoryStream("first"u8.ToArray());
    using var reader = new StreamReader(stream, leaveOpen: true);
    return reader.ReadLine();
}

The program prints first. The reader and stream are disposed in reverse declaration order even when reading throws. Replace the memory stream with File.OpenRead to read an existing file.

Delegates & Events

Delegates hold callable methods and events control notification subscriptions. Publishers can retain subscribers, so unsubscribe when their lifetimes should end independently.

Call behavior through a delegate

csharp
// Delegate type declaration
public delegate int Transform(int value);

// Built-in generic delegates
Action<string> log    = msg => Console.WriteLine($'[LOG] {msg}');
Func<int, int> square = x   => x * x;
Predicate<int> isEven = n   => n % 2 == 0;

// Multicast delegate — all subscribers called in order
Action<string> notify = s => Console.WriteLine($'Handler1: {s}');
notify += s => Console.WriteLine($'Handler2: {s}');
notify('event fired');   // both handlers run

The signature controls which methods can be assigned. Combining delegates calls the handlers in registration order.

Publish and subscribe to an event

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Custom EventArgs
public class ValueChangedEventArgs : EventArgs {
    public int OldValue { get; }
    public int NewValue { get; }
    public ValueChangedEventArgs(int oldVal, int newVal) {
        OldValue = oldVal; NewValue = newVal;
    }
}

// Class with event
public class Counter {
    private int _value;
    public event EventHandler<ValueChangedEventArgs>? ValueChanged;

    public int Value {
        get => _value;
        set {
            ValueChanged?.Invoke(this, new ValueChangedEventArgs(_value, value));
            _value = value;
        }
    }
}

// Subscribe / unsubscribe
var counter = new Counter();
EventHandler<ValueChangedEventArgs> handler =
    (_, e) => Console.WriteLine($'{e.OldValue} -> {e.NewValue}');
counter.ValueChanged += handler;
counter.Value = 10;              // fires: 0 -> 10
counter.ValueChanged -= handler; // unsubscribe

// Lambda stored as typed delegate
Transform doubleIt = x => x * 2;
int res = doubleIt(5);   // 10

The publisher supplies event data to subscribers. Removing the handler stops subsequent notifications to it.

Extension Methods

Extension methods provide static helper calls with instance-like syntax. They neither change the target type nor override its instance methods.

Extend strings and sequences

csharp
// Extension methods live in a static class
public static class StringExtensions {
    // 'this' marks the type being extended
    public static bool IsPalindrome(this string s) {
        s = new string(s.ToLower().Where(char.IsLetter).ToArray());
        return s == new string(s.Reverse().ToArray());
    }

    public static string Truncate(this string s, int maxLen, string suffix = '...') =>
        s.Length <= maxLen ? s : s[..maxLen] + suffix;
}

// Extending IEnumerable<T>
public static class EnumerableExtensions {
    public static IEnumerable<T> WhereNotNull<T>(
        this IEnumerable<T?> source) where T : class
        => source.Where(x => x is not null)!;

    public static IEnumerable<(int Index, T Item)> Indexed<T>(
        this IEnumerable<T> source)
        => source.Select((item, i) => (i, item));
}

// Usage
bool palindrome  = 'racecar'.IsPalindrome();      // true
string truncated = 'Hello World'.Truncate(5);     // 'Hello...'

var names = new[] { 'Alice', null, 'Bob', null };
foreach (var (i, name) in names.WhereNotNull().Indexed()) {
    Console.WriteLine($'{i}: {name}');
}

The receiver is passed as the first argument of the static extension method.

Chain builder operations

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Fluent builder pattern via extension methods
public static class BuilderExtensions {
    public static StringBuilder AppendLineIf(
        this StringBuilder sb, bool condition, string text) =>
        condition ? sb.AppendLine(text) : sb;
}

string msg = new StringBuilder()
    .AppendLine('Hello')
    .AppendLineIf(true,  'World')
    .AppendLineIf(false, 'Ignored')
    .ToString();

Returning the builder lets the caller pass the result directly to the next extension method.

Span<T> & Memory<T>

Span is a constrained view over contiguous memory; Memory can be retained across asynchronous boundaries. Both permit working with buffer slices without copying their contents.

Slice and parse contiguous data

csharp
// Span<T> — stack-only, zero-allocation slice over contiguous memory
int[] array = { 1, 2, 3, 4, 5 };
Span<int> span  = array.AsSpan();
Span<int> slice = span[1..4];   // { 2, 3, 4 } — no copy

// Slicing strings without allocation
ReadOnlySpan<char> text = 'Hello, World!'.AsSpan();
ReadOnlySpan<char> word = text[..5];   // 'Hello' — no string allocation

// Parsing without allocations
ReadOnlySpan<char> csv = '42,100,7'.AsSpan();
while (csv.Length > 0) {
    int comma = csv.IndexOf(',');
    var part  = comma < 0 ? csv : csv[..comma];
    int.TryParse(part, out int num);
    Console.WriteLine(num);
    csv = comma < 0 ? ReadOnlySpan<char>.Empty : csv[(comma + 1)..];
}

// stackalloc — allocate on stack, wrap in Span
Span<byte> buffer = stackalloc byte[64];
buffer.Fill(0);

Slicing creates a view over existing storage. Parsing the character span avoids allocating a substring.

Carry a buffer across an await

csharp
// Memory<T> — heap-safe, works across async boundaries
Memory<int> memory = new Memory<int>(array, 1, 3);
await ProcessAsync(memory);   // safe to pass to async methods

static async Task ProcessAsync(Memory<int> mem) {
    await Task.Yield();
    Span<int> s = mem.Span;   // access Span inside a sync scope
    foreach (var item in s) Console.WriteLine(item);
}

// MemoryMarshal — reinterpret raw memory
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x01, 0x00, 0x00, 0x00 };
int value = System.Runtime.InteropServices.MemoryMarshal.Read<int>(bytes);

Keep Memory across suspension and obtain a span when accessing the buffer synchronously.

Advanced Collections

Choose collections by ordering, lookup, mutation, and concurrency needs. Thread-safe individual operations do not automatically protect a multi-step application invariant.

Choose a collection by its operations

csharp
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections.Immutable;

// Interface hierarchy
IEnumerable<int>  seq  = new List<int> { 1, 2, 3 };   // read-only iteration
ICollection<int>  coll = new List<int> { 1, 2, 3 };   // Count + Add/Remove
IList<int>        list = new List<int> { 1, 2, 3 };   // index access

// LinkedList — O(1) insert/remove at a known node
var linked = new LinkedList<string>(new[] { 'alpha', 'beta', 'gamma' });
linked.AddFirst('zeta');
linked.Remove('beta');

// SortedDictionary — keys always sorted (Red-Black tree, O(log n))
var sorted = new SortedDictionary<string, int> {
    ['banana'] = 2, ['apple'] = 5, ['cherry'] = 1
};

// HashSet — set operations
var a = new HashSet<int> { 1, 2, 3, 4 };
var b = new HashSet<int> { 3, 4, 5, 6 };
a.IntersectWith(b);   // a == { 3, 4 }
a.UnionWith(b);       // a == { 3, 4, 5, 6 }

A linked list supports insertion at a known node. A sorted dictionary orders keys, and a set models membership.

Share, copy and reuse collection storage

csharp
// ConcurrentDictionary — thread-safe without external locking
var cc = new ConcurrentDictionary<string, int>();
cc.AddOrUpdate('hits', 1, (k, old) => old + 1);
int val = cc.GetOrAdd('missing', _ => 42);

// ImmutableList — returns new instance on each mutation
ImmutableList<int> imm  = ImmutableList.Create(1, 2, 3);
ImmutableList<int> imm2 = imm.Add(4);   // original unchanged

// ArrayPool — reuse large buffers to reduce GC pressure
var pool   = System.Buffers.ArrayPool<byte>.Shared;
byte[] buf = pool.Rent(1024);
try { /* use buf */ } finally { pool.Return(buf); }

// Custom IEqualityComparer
public class CaseInsensitiveComparer : IEqualityComparer<string> {
    public bool Equals(string? x, string? y) =>
        string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
    public int GetHashCode(string obj) =>
        obj.ToLowerInvariant().GetHashCode();
}
var dict = new Dictionary<string, int>(new CaseInsensitiveComparer());

Concurrent operations support shared updates. Immutable updates return a new value, and rented arrays must be returned.

Reflection & Attributes

Reflection inspects runtime metadata and attributes attach declarative information. Keep reflective access focused because it shifts some errors from compilation to execution.

Inspect runtime type metadata

csharp
using System;
using System.Reflection;

// Custom attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuditAttribute : Attribute {
    public string Action { get; }
    public AuditAttribute(string action) => Action = action;
}

[Audit('UserLogin')]
public class AuthService {
    [Audit('GetUser')]
    public string GetUser(int id) => $'User-{id}';

    [Obsolete('Use GetUser instead')]
    public string FetchUser(int id) => GetUser(id);
}

// Inspect type at runtime
Type t = typeof(AuthService);
Console.WriteLine(t.FullName);

foreach (var prop in t.GetProperties())
    Console.WriteLine($'{prop.Name}: {prop.PropertyType.Name}');

foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
    Console.WriteLine($'{m.Name}({m.GetParameters().Length} params)');

The Type object exposes members and the attribute definition specifies metadata that can be attached to a class.

Read attributes and invoke members

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Read custom attribute
var attr = t.GetCustomAttribute<AuditAttribute>();
Console.WriteLine(attr?.Action);   // 'UserLogin'

// Activator.CreateInstance — instantiate by type
object instance = Activator.CreateInstance(typeof(AuthService))!;

// MethodInfo.Invoke — dynamic method invocation
MethodInfo? method = t.GetMethod('GetUser');
object? result = method?.Invoke(instance, new object[] { 42 });
Console.WriteLine(result);   // 'User-42'

// CallerMemberName — inject caller name at compile time (no reflection cost)
public static void Log(string msg,
    [System.Runtime.CompilerServices.CallerMemberName] string caller = '') =>
    Console.WriteLine($'[{caller}] {msg}');

Log('started');   // [MyMethod] started

Use the annotated type from the first fragment. Reflection can retrieve its attribute and invoke a selected method at runtime.

Source Generators & Modern C#

Source generators inspect compilation inputs and add source during a build. Generated code undergoes normal compilation instead of requiring runtime reflection for that work.

Run each example separately in the starter console project.

Partial types and optional hooks

csharp
new OrderService().CreateOrder(7);

partial class OrderService
{
    public void CreateOrder(int id)
    {
        Console.WriteLine($"Created {id}");
        OnOrderCreated(id);
    }

    partial void OnOrderCreated(int id);
}

partial class OrderService
{
    partial void OnOrderCreated(int id) => Console.WriteLine($"Audit {id}");
}

The compiler combines both declarations into one type, even when they live in separate files. This example prints Created 7 and Audit 7. Delete the second declaration and the optional partial void call disappears, leaving only Created 7. A generator can supply a partial declaration during compilation, using inputs such as attributes to decide what source to add.

Generating a regular expression

csharp
using System.Text.RegularExpressions;

foreach (string input in new[] { "2024-01-15", "2024/01/15", "2024-99-99" })
    Console.WriteLine(DatePatterns.HasDateShape(input));

static partial class DatePatterns
{
    public static bool HasDateShape(string input) => DateShape().IsMatch(input);

    [GeneratedRegex(@"\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z")]
    private static partial Regex DateShape();
}

Use GeneratedRegex for a pattern known at build time. The attribute provides the pattern and the generator supplies the method implementation in another declaration of the partial class. The outputs are True, False, and True. The last input has the right shape. Use DateOnly.TryParseExact if you also need to validate the calendar date.

Using generated JSON metadata

csharp
using System.Text.Json;
using System.Text.Json.Serialization;

var config = new Config { Host = "localhost", Port = 5432 };
var contract = ConfigJsonContext.Default.Config;
string json = JsonSerializer.Serialize(config, contract);
Config restored = JsonSerializer.Deserialize(json, contract)
    ?? throw new JsonException("Expected a config object.");

Console.WriteLine(json);
Console.WriteLine(restored.Host == config.Host &&
    restored.Port == config.Port && restored.Scheme == config.Scheme);

public sealed class Config
{
    public required string Host { get; init; }
    public required int Port { get; init; }
    public string Scheme { get; init; } = "https";
}

[JsonSerializable(typeof(Config))]
internal partial class ConfigJsonContext : JsonSerializerContext { }

JsonSerializable registers Config as a generation input. The generated Config property provides the contract used explicitly in both serializer calls. The JSON contains localhost, 5432, and https, and the round trip prints True. The initializer must supply Host and Port because they are required. The init accessors allow initialization and prevent later assignment.

To inspect generator output, run dotnet build -p:EmitCompilerGeneratedFiles=true from the project directory. Look under obj/Debug/net10.0/generated for the generated source files.

Keeping a helper local to a file

csharp
Console.WriteLine(ScaleHelper.Double(21));

file static class ScaleHelper
{
    public static int Double(int value) => value * 2;
}

This prints 42. Put a reference to ScaleHelper in a second source file and the compiler cannot resolve it there. File-local types let generated files or handwritten files use helper names independently.

Wrapping a span in a ref struct

csharp
Span<byte> bytes = stackalloc byte[2];
var buffer = new StackBuffer(bytes);
buffer.SetFirst(7);
Console.WriteLine($"{buffer.Length}, {bytes[0]}");

ref struct StackBuffer(Span<byte> data)
{
    private Span<byte> _data = data;

    public int Length => _data.Length;
    public void SetFirst(byte value) => _data[0] = value;
}

The output is 2, 7. The wrapper stores a span over the original buffer, so SetFirst changes the same bytes. A ref struct can hold that span. The compiler prevents boxing it or storing it in a class field so the view cannot escape through the heap.

Choosing an overflow policy

csharp
int max = int.MaxValue;
Console.WriteLine(unchecked(max + 1));

try
{
    Console.WriteLine(checked(max + 1));
}
catch (OverflowException)
{
    Console.WriteLine("Overflow");
}

Unchecked addition wraps from the largest int to -2147483648. Checked addition throws before WriteLine receives a value, so the handler prints Overflow. Use checked when wrapping would corrupt a count or total.

For embedded JSON text, see the raw string literals lesson.

Unsafe Code & Fixed Buffers

The unsafe keyword enables pointer arithmetic, fixed pinning, and stack allocation with stackalloc. For most high-performance scenarios, Span<T> and Memory<T> cover the same ground without unsafe.

Compile pointer and fixed-buffer examples in a project with AllowUnsafeBlocks enabled.

Dereference and advance a pointer

csharp
// Enable: <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in .csproj
// Compile: dotnet build -p:AllowUnsafeBlocks=true

unsafe void PointerBasics() {
    int x = 42;
    int* p = &x;
    Console.WriteLine(*p);   // 42
    *p = 100;
    Console.WriteLine(x);    // 100

    // Pointer arithmetic
    int[] arr = { 1, 2, 3 };
    fixed (int* ptr = arr) {
        for (int i = 0; i < arr.Length; i++)
            Console.Write(*(ptr + i) + ' ');
    }
}

Dereferencing reads or writes the addressed value. Pointer arithmetic advances in units of the element type.

Pin a managed object or use stack storage

csharp
// Use the relevant setup or declarations from the preceding fragment.
// fixed — pin a managed object so GC won't move it
unsafe void CopyBytes(byte[] src, byte[] dst) {
    fixed (byte* s = src, d = dst) {
        Buffer.MemoryCopy(s, d, dst.Length, src.Length);
    }
}

// Stackalloc — allocate on the stack (no GC, no heap)
unsafe void StackBuffer() {
    int* buf = stackalloc int[64];
    for (int i = 0; i < 64; i++) buf[i] = i * i;
    Console.WriteLine(buf[7]);   // 49
}

// Span<T> + stackalloc (safe equivalent — no unsafe needed)
Span<int> span = stackalloc int[64];
span.Fill(0);
span[3] = 99;

A fixed block keeps a managed object in place for the pointer’s use. A span can wrap stack storage with bounds checks.

Channels & IAsyncEnumerable

Channel<T> provides a thread-safe asynchronous queue for producer-consumer pipelines. IAsyncEnumerable<T> combined with await foreach enables streaming async sequences with cancellation support.

A bounded channel can make a producer wait for capacity when its full mode is Wait. An unbounded channel grows as items are queued. Complete the writer when production ends so readers can finish after consuming the remaining items.

Send and receive values through a bounded channel

csharp
using System.Threading.Channels;
using System.Runtime.CompilerServices;

// Channel<T> — async producer/consumer pipeline
var ch = Channel.CreateBounded<int>(capacity: 10);

// Producer
async Task ProduceAsync() {
    for (int i = 0; i < 100; i++) {
        await ch.Writer.WriteAsync(i);
    }
    ch.Writer.Complete();
}

// Consumer
async Task ConsumeAsync() {
    await foreach (int item in ch.Reader.ReadAllAsync()) {
        Console.WriteLine(item);
    }
}

await Task.WhenAll(ProduceAsync(), ConsumeAsync());

The producer awaits available capacity. Completing the writer lets the consumer finish after draining the channel.

Yield and consume an asynchronous sequence

csharp
using System.Runtime.CompilerServices;
using System.Threading.Channels;

// IAsyncEnumerable<T> — async iteration (C# 8)
async IAsyncEnumerable<int> StreamNumbers(
    [EnumeratorCancellation] CancellationToken ct = default)
{
    for (int i = 0; i < 10; i++) {
        await Task.Delay(100, ct);
        yield return i;
    }
}

await foreach (int n in StreamNumbers().WithCancellation(CancellationToken.None)) {
    Console.WriteLine(n);
}

// Unbounded channel (drop-in for high-throughput)
var unbounded = Channel.CreateUnbounded<string>();

await foreach awaits successive values. An unbounded channel lets queued items accumulate without a fixed capacity.

Expression Trees

Expression trees represent code as inspectable data structures — instead of compiling to IL, the lambda is stored as an AST. LINQ providers (Entity Framework, LINQ-to-SQL) use this to translate C# expressions into SQL queries at runtime.

Inspect and compile a lambda tree

csharp
using System.Linq.Expressions;

// Expression tree — code as data, inspectable at runtime
// The lambda (x => x * x) compiles to an expression tree, not IL
Expression<Func<int, int>> expr = x => x * x;

// Inspect the tree
var body     = (BinaryExpression)expr.Body;
var left     = (ParameterExpression)body.Left;
Console.WriteLine(body.NodeType);   // Multiply
Console.WriteLine(left.Name);       // x

// Compile and invoke
Func<int, int> fn = expr.Compile();
Console.WriteLine(fn(5));           // 25

Inspect the nodes to see the operation represented by the lambda. Compile creates an invocable delegate.

Build a predicate from expression nodes

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Build an expression tree manually
ParameterExpression param = Expression.Parameter(typeof(int), 'n');
Expression body2 = Expression.Add(param, Expression.Constant(1));
var lambda = Expression.Lambda<Func<int, int>>(body2, param);
Console.WriteLine(lambda.Compile()(10));  // 11

// Practical use: build a dynamic WHERE predicate for LINQ-to-SQL/EF
Expression<Func<Product, bool>> BuildFilter(string field, string value) {
    var param = Expression.Parameter(typeof(Product), 'p');
    var member = Expression.Property(param, field);
    var constant = Expression.Constant(value);
    var equals = Expression.Equal(member, constant);
    return Expression.Lambda<Func<Product, bool>>(equals, param);
}
// dbContext.Products.Where(BuildFilter('Name', 'Widget')).ToList()

The parameter node ties member access to the lambda input. Query providers can inspect the resulting predicate.

Generic Variance

Covariance (out) lets you use IEnumerable<Derived> where IEnumerable<Base> is expected. Contravariance (in) goes the other way. Both are declared on the interface/delegate type parameter.

Use variance in assignments

csharp
// Covariance (out) — can use a more derived type as the type argument
// IEnumerable<out T> — safe because T only comes OUT (returned)
IEnumerable<string> strings = new List<string> { 'a', 'b' };
IEnumerable<object> objects = strings;   // OK — covariant

// Contravariance (in) — can use a less derived type as the type argument
// IComparer<in T> — safe because T only goes IN (consumed)
IComparer<object> objCmp = Comparer<object>.Default;
IComparer<string> strCmp = objCmp;   // OK — contravariant

// Invariant — not co- or contravariant (e.g. IList<T>)
// IList<object> list = new List<string>();  // compile error

Covariance widens the produced type. Contravariance allows a consumer of a broader type to handle a narrower type.

Declare variant parameters and constraints

csharp
// Defining a covariant interface
interface IProducer<out T> {
    T Produce();   // T only in output position
}

// Defining a contravariant interface
interface IConsumer<in T> {
    void Consume(T item);   // T only in input position
}

// Generic constraints
void Process<T>(T value) where T : IComparable<T>, new() { }
T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) > 0 ? a : b;

// Unconstrained generic utilities
T Identity<T>(T x) => x;
T[] Repeat<T>(T value, int count) => Enumerable.Repeat(value, count).ToArray();

Mark output-only parameters with out and input-only parameters with in. Constraints govern which type arguments a generic declaration accepts.

P/Invoke & Native Interop

P/Invoke lets C# call functions in native shared libraries. Use [LibraryImport] (C# 11) over the older [DllImport] for source-generated, AOT-compatible bindings. StructLayout controls struct memory layout for wire protocols.

These declarations require the native library and entry point named in each signature. Check the target operating system and calling convention before invoking them.

Declare a native function binding

csharp
using System.Runtime.InteropServices;

// P/Invoke — call native C functions from C#
internal static partial class NativeMethods {
    // Classic P/Invoke
    [DllImport('user32.dll', CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

    // LibraryImport (C# 11 source-generated, preferred over DllImport)
    [LibraryImport('libc', EntryPoint = 'getpid')]
    public static partial int GetPid();

    [LibraryImport('libm', EntryPoint = 'sqrt')]
    public static partial double Sqrt(double x);
}

Match the native library name and signature for the platform before invoking the function.

Control layout and pin managed storage

csharp
// Struct layout — control memory representation for interop
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct PacketHeader {
    public byte  Type;
    public short Length;
    public int   Checksum;
}

// Marshal — convert between managed and unmanaged memory
string managed = Marshal.PtrToStringAnsi(ptr);
IntPtr unmanaged = Marshal.StringToHGlobalAnsi('hello');
Marshal.FreeHGlobal(unmanaged);

// GCHandle — pin a managed object so unmanaged code can hold a pointer
byte[] buffer = new byte[1024];
var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr addr = handle.AddrOfPinnedObject();
// pass addr to native code...
handle.Free();   // MUST free when done

Match native field layout. Release a pinned handle after native code has finished using the address.

Primary Constructors (C# 12)

Primary constructors let you declare constructor parameters directly on the class or struct declaration. The parameters are in scope throughout the entire type body — field initializers, methods, and properties can all reference them, eliminating boilerplate assignment code and making dependency injection feel natural.

Initialize classes and base types

csharp
// C# 12 primary constructors — parameters available throughout the class body
public class Logger(string name, LogLevel minLevel) {
    // Parameters are in scope for field initializers and all methods
    private readonly string _prefix = $'[{name}]';

    public void Log(LogLevel level, string msg) {
        if (level >= minLevel)
            Console.WriteLine($'{_prefix} {level}: {msg}');
    }
}

// Inheritance — pass primary constructor args to base
public class ConsoleLogger(string name, LogLevel minLevel, bool useColor)
    : Logger(name, minLevel) {
    public void Warn(string msg) {
        if (useColor) Console.ForegroundColor = ConsoleColor.Yellow;
        Log(LogLevel.Warning, msg);
        if (useColor) Console.ResetColor();
    }
}

Primary constructor parameters are in scope in the class body and can be passed to a base constructor.

Use primary constructors across type declarations

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Structs also support primary constructors
public struct Vector2(double x, double y) {
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Length => Math.Sqrt(X * X + Y * Y);
    public Vector2 Normalized => new(X / Length, Y / Length);
    public override string ToString() => $'({X:F2}, {Y:F2})';
}

// Records already had primary constructors; now classes/structs do too
public class ServiceClient(HttpClient http, string baseUrl, ILogger logger) {
    public async Task<string> GetAsync(string path) {
        logger.LogInformation('GET {Url}', baseUrl + path);
        return await http.GetStringAsync(baseUrl + path);
    }
    public async Task PostAsync<T>(string path, T body) {
        logger.LogInformation('POST {Url}', baseUrl + path);
        await http.PostAsJsonAsync(baseUrl + path, body);
    }
}

// DI-friendly — constructor params naturally map to injected services
public class OrderService(
    IOrderRepository repo,
    IEventBus events,
    ILogger<OrderService> log) {
    public async Task<Order> CreateAsync(CreateOrderRequest req) {
        var order = new Order(req.CustomerId, req.Items);
        await repo.SaveAsync(order);
        await events.PublishAsync(new OrderCreated(order.Id));
        log.LogInformation('Order {Id} created', order.Id);
        return order;
    }
}

A class or struct can use parameters to initialize members. A positional record also synthesizes properties.

Collection Expressions (C# 12)

Collection expressions provide a single, unified [...] syntax for creating arrays, lists, spans, and other supported collection types. The spread operator .. adds elements from another sequence. The target type determines the resulting collection.

Create and combine collections

csharp
// C# 12 collection expressions — uniform syntax for any collection type
// Arrays
int[] squares = [1, 4, 9, 16, 25];

// List<T>
List<string> names = ["Alice", "Bob", "Carol"];

// Span<T> / ReadOnlySpan<T> — stack allocation when possible
Span<byte> flags = [0x01, 0x02, 0x04, 0x08];

// Spread operator (..) — inline another collection
int[] first  = [1, 2, 3];
int[] second = [4, 5, 6];
int[] all    = [..first, ..second, 7, 8];   // [1,2,3,4,5,6,7,8]

// Collection targets can supply their own construction rules
HashSet<int> set = [1, 2, 3, 2, 1];   // {1, 2, 3}
ImmutableArray<string> immutable = ["x", "y", "z"];

The target type determines the collection representation. A spread inserts elements from another sequence.

Use collection expressions in typed contexts

csharp
// Spread in method arguments
void PrintAll(params IEnumerable<int> nums) {
    foreach (var n in nums) Console.Write($"{n} ");
}
int[] extra = [10, 20];
PrintAll([1, 2, ..extra, 30]);   // 1 2 10 20 30

// Dictionary initializer
Dictionary<string, int> scores = new() {
    ["Alice"] = 95,
    ["Bob"]   = 87,
};

// Useful for default / empty collection constants
int[] empty = [];

// Target-typed — the compiler infers the collection type from context
IReadOnlyList<string> colors = ["red", "green", "blue"];
ReadOnlySpan<char> vowels    = ['a', 'e', 'i', 'o', 'u'];

// Nested collections
int[][] matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

The parameter or assignment provides the target type, including for empty and nested expressions.

Raw String Literals

Raw string literals (C# 11) are delimited by three or more double-quote characters and require no escape sequences — backslashes, quotes, and curly braces are all literal. Leading whitespace matching the closing delimiter is automatically stripped, keeping embedded JSON, SQL, HTML, and regex patterns readable without noise.

Write literal text without escapes

csharp
// Raw string literals (C# 11+) — delimited by 3+ double quotes
// No escape sequences: backslash, quotes, braces are literal
string path = """C:\Users\Alice\Documents\file.txt""";
string json = """
    {
        'name': 'Alice',
        'scores': [95, 87, 92]
    }
    """;

A raw delimiter preserves characters such as backslashes and embedded quotes.

Interpolate and indent raw text

csharp
// Interpolation inside raw strings — prefix with $
string name = "Alice";
int age  = 30;
string html = $"""
    <div class='user'>
        <span>{name}</span>
        <span>{age}</span>
    </div>
    """;

// With two dollar signs, two braces delimit interpolation.
string tableName = "Orders";
int id = 42;
string template = $$"""
    SELECT * FROM {{tableName}}
    WHERE id = {{id}};
    """;

// Indentation: leading whitespace equal to the closing quotes is stripped
// The result is properly de-indented — no leading spaces in the output
string xml = """
    <root>
        <child attr='value'>text</child>
    </root>
    """;

// Embed quotes freely — no escaping needed
string sql = """
    SELECT 'literal string', "quoted identifier"
    FROM schema.'table name'
    WHERE name = 'O''Brien'
    """;

// Useful for regex patterns — no double-escaping needed
var pattern = new System.Text.RegularExpressions.Regex("""d{4}-d{2}-d{2}""");
bool ok = pattern.IsMatch('2024-07-04');   // true

// Single-line raw strings
string greeting = """Hello, "World"!""";

The dollar count sets the required number of braces for interpolation. Closing delimiter indentation sets the indentation removed from each line.

Advanced LINQ

Run each example separately in the starter console project.

Beyond basic filtering and projection, LINQ offers powerful set operations, multi-level grouping, joins between heterogeneous sequences, and operators such as MinBy, MaxBy, DistinctBy, and Chunk. ILookup<K,V> is a read-only multi-valued dictionary built in one pass.

Aggregating and indexing groups

csharp
var products = new[] { (Name: "Saw", Category: "Tools", Price: 30, Stock: 2),
    (Name: "Drill", Category: "Tools", Price: 60, Stock: 5),
    (Name: "Lamp", Category: "Home", Price: 20, Stock: 1) };

var report = products.GroupBy(p => p.Category)
    .Select(g => new { g.Key, Count = g.Count(), Total = g.Sum(p => p.Price),
        Average = g.Average(p => p.Price), Highest = g.Max(p => p.Price) })
    .OrderByDescending(g => g.Total);
foreach (var row in report)
    Console.WriteLine($"{row.Key}: {row.Count}, {row.Total}, {row.Average}, {row.Highest}");

var lookup = products.ToLookup(p => p.Category);
Console.WriteLine(string.Join(", ", lookup["Tools"].Select(p => p.Name)));
Console.WriteLine(lookup["Missing"].Count());
Console.WriteLine(products.MinBy(p => p.Price).Name);
Console.WriteLine(products.MaxBy(p => p.Stock).Name);
Console.WriteLine(products.DistinctBy(p => p.Category).Count());

Tools appears first with count 2, total 90, average 45, and maximum 60. ToLookup immediately indexes the products by category. Tools yields Saw and Drill, while Missing yields zero items. MinBy and MaxBy return the original products Lamp and Drill. DistinctBy keeps one product per category, leaving two.

Joining orders to prices

csharp
var orders = new[] { (Name: "Saw", Quantity: 3), (Name: "Missing", Quantity: 1) };
var prices = new[] { (Name: "Saw", Price: 30) };

var totals = orders.Join(prices, order => order.Name, price => price.Name,
    (order, price) => (order.Name, Total: order.Quantity * price.Price));
foreach (var row in totals)
    Console.WriteLine($"{row.Name}: {row.Total}");

The only line is Saw: 90. Join yields one row per matching pair. Missing has no matching price, and a second Saw price would yield a second row.

Flattening, pairing, and batching sequences

csharp
var lists = new[] { (Name: "A", Tags: new[] { "x", "y" }), (Name: "B", Tags: new[] { "z" }) };
var tags = lists.SelectMany(list => list.Tags, (list, tag) => $"{list.Name}:{tag}");
Console.WriteLine(string.Join(", ", tags));

string[] names = ["Alice", "Bob", "Carol"];
int[] scores = [95, 87];
Console.WriteLine(string.Join(", ", names.Zip(scores, (name, score) => $"{name}:{score}")));

foreach (var batch in names.Chunk(2))
    Console.WriteLine(string.Join(", ", batch));

string[] requested = ["Alice", "Dana", "Dana"];
Console.WriteLine(string.Join(", ", requested.Except(names)));

SelectMany emits A:x, A:y, B:z. Zip stops at the shorter sequence and pairs only Alice and Bob with scores. Chunk yields Alice and Bob in the first batch and Carol in the final batch. Except returns Dana once because it returns distinct values absent from names.

Memory & GC

The .NET GC is generational and largely automatic, but high-throughput code benefits from reducing allocations via ArrayPool<T>, the dispose pattern for deterministic cleanup, WeakReference<T> for cache-friendly handles, and MemoryMarshal for zero-copy reinterpretation of raw bytes.

Dispose resources at a predictable time

csharp
using System;
using System.Runtime;
using System.Buffers;

// IDisposable pattern — deterministic cleanup of unmanaged resources
public class FileProcessor : IDisposable {
    private FileStream? _stream;
    private bool _disposed;

    public FileProcessor(string path) => _stream = File.OpenRead(path);

    public int Read(byte[] buf) {
        ObjectDisposedException.ThrowIf(_disposed, this);
        return _stream!.Read(buf);
    }

    protected virtual void Dispose(bool disposing) {
        if (_disposed) return;
        if (disposing) _stream?.Dispose();   // managed resources
        _disposed = true;
    }

    public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
    ~FileProcessor() => Dispose(false);    // finalizer as safety net
}

// using declaration — dispose at end of enclosing scope
using var fp = new FileProcessor('data.bin');

A using declaration disposes its resource when the enclosing scope ends.

Reuse buffers and inspect managed memory

csharp
// Use the relevant setup or declarations from the preceding fragment.
// ArrayPool — avoid allocating large short-lived arrays
var pool = ArrayPool<byte>.Shared;
byte[] buf = pool.Rent(4096);
try {
    int read = fp.Read(buf);
    Process(buf.AsSpan(0, read));
} finally {
    pool.Return(buf, clearArray: false);
}

// GC.Collect — rarely needed; useful in benchmarks
GC.Collect(2, GCCollectionMode.Forced, blocking: true);
GC.WaitForPendingFinalizers();

// WeakReference — let GC collect if memory is needed
var cache = new WeakReference<byte[]>(new byte[1024 * 1024]);
if (!cache.TryGetTarget(out var data))
    data = LoadData();

// GCSettings — server vs workstation GC
Console.WriteLine(GCSettings.IsServerGC);        // true in ASP.NET
Console.WriteLine(GCSettings.LatencyMode);       // default: Interactive

// MemoryMarshal — reinterpret bytes without copy
Span<byte> raw = stackalloc byte[8];
MemoryMarshal.Write(raw, 3.14);
double back = MemoryMarshal.Read<double>(raw);   // 3.14

Return a rented buffer after use. A weak reference allows collection of its target when strong references disappear.

Threading Primitives

The BCL offers a layered threading toolkit: Interlocked for lock-free atomic ops, SemaphoreSlim for async-compatible throttling, ReaderWriterLockSlim for read-heavy workloads, ConcurrentQueue for thread-safe FIFO, and Parallel.ForEachAsync for bounded async fan-out.

Protect critical sections and limit access

csharp
using System.Threading;
using System.Collections.Concurrent;

// Mutex — system-wide exclusive lock (cross-process capable)
using var mutex = new Mutex(false, 'Global\\MyAppSingleInstance');
if (!mutex.WaitOne(0)) { Console.WriteLine('Already running'); return; }

// SemaphoreSlim — async-friendly, limits concurrency
var sem = new SemaphoreSlim(3);   // max 3 concurrent
async Task ThrottledWorkAsync() {
    await sem.WaitAsync();
    try { await DoWorkAsync(); }
    finally { sem.Release(); }
}

// ReaderWriterLockSlim — multiple readers OR one writer
var rwLock = new ReaderWriterLockSlim();
string _sharedData = '';
string Read() {
    rwLock.EnterReadLock();
    try { return _sharedData; }
    finally { rwLock.ExitReadLock(); }
}
void Write(string val) {
    rwLock.EnterWriteLock();
    try { _sharedData = val; }
    finally { rwLock.ExitWriteLock(); }
}

A semaphore caps concurrent access. A reader-writer lock can admit several readers when no writer holds it.

Update atomically and coordinate workers

csharp
// Interlocked — atomic operations without locks
int _counter = 0;
Interlocked.Increment(ref _counter);
Interlocked.Add(ref _counter, 5);
int old = Interlocked.Exchange(ref _counter, 0);   // reset, return old
Interlocked.CompareExchange(ref _counter, 10, 0);  // set to 10 only if 0

// ConcurrentQueue — thread-safe FIFO
var queue = new ConcurrentQueue<int>();
queue.Enqueue(1);
if (queue.TryDequeue(out int item)) Console.WriteLine(item);

// Parallel.ForEachAsync (C# 6+) — bounded async parallelism
await Parallel.ForEachAsync(
    Enumerable.Range(0, 100),
    new ParallelOptions { MaxDegreeOfParallelism = 4 },
    async (i, ct) => await ProcessItemAsync(i, ct));

// ManualResetEventSlim — signal one or many threads
var ready = new ManualResetEventSlim(false);
Task.Run(() => { Thread.Sleep(500); ready.Set(); });
ready.Wait();
Console.WriteLine('Signal received');

Interlocked applies an atomic update. A concurrent queue transfers items, and an event can signal waiting threads.

Indexers & Ranges

System.Index and System.Range generalize indexing and slicing beyond arrays. A Length/Count property can participate in support for ^n (from-end) and start..end syntax. Custom types can opt in by adding compatible indexers.

The end of a range is exclusive. A range from 1 to 3 selects indexes 1 and 2. The index ^1 denotes the last item, while ^0 denotes the position just past the last item and works as a range boundary. Custom types need compatible members for the syntax they support.

Expose indexed access on a type

csharp
// Indexers — allow [] access on custom types
public class Grid<T> {
    private readonly T[,] _data;
    public int Rows { get; }
    public int Cols { get; }

    public Grid(int rows, int cols) {
        Rows = rows; Cols = cols;
        _data = new T[rows, cols];
    }

    // 2D indexer
    public T this[int row, int col] {
        get => _data[row, col];
        set => _data[row, col] = value;
    }

    // Slicing a row via Index
    public T[] this[int row, Range cols] {
        get {
            var (offset, len) = cols.GetOffsetAndLength(Cols);
            var result = new T[len];
            Array.Copy(_data, row * Cols + offset, result, 0, len);
            return result;
        }
    }
}

The indexer controls how bracket syntax maps to backing storage.

Compute indices and slices

csharp
// System.Index — ^ means 'from end'
int[] arr = { 10, 20, 30, 40, 50 };
int last      = arr[^1];   // 50
int secondLast = arr[^2];  // 40

// System.Range — start..end (end exclusive)
int[] middle  = arr[1..4];    // [20, 30, 40]
int[] fromTwo = arr[2..];     // [30, 40, 50]
int[] toThree = arr[..3];     // [10, 20, 30]
int[] copy    = arr[..];      // full copy

// Ranges on strings — returns string (not span)
string s   = "Hello, World!";
string sub = s[7..12];   // 'World'
string end = s[^6..];    // 'World!'

// Ranges with Span<T> — zero copy slice
Span<int> span  = arr.AsSpan();
Span<int> slice = span[1..^1];   // [20, 30, 40]

// Index / Range as variables
Index  fromEnd = ^1;
Range  mid     = 1..4;
var    midArr  = arr[mid];   // [20, 30, 40]

// GetOffsetAndLength — compute slice bounds manually
(int offset, int length) = mid.GetOffsetAndLength(arr.Length);

The end of a range is exclusive. A span slice views the same storage, while slicing a string produces a string result.

Nullable Reference Types

Enable <Nullable>enable</Nullable> in your project to get flow-sensitive null analysis. The compiler tracks nullability through conditionals, pattern matches, and method contracts expressed via attributes like [NotNullWhen], turning null-dereference bugs into compile-time warnings.

Declare nullable intent

csharp
// Enable nullable analysis: <Nullable>enable</Nullable> in .csproj
// Compiler now distinguishes string (never null) from string? (maybe null)

// Non-nullable — guaranteed non-null, no null-check warnings
string name = 'Alice';

// Nullable — might be null; compiler warns on unsound dereference
string? middle = null;
Console.WriteLine(middle?.ToUpper() ?? '(none)');

// Null-forgiving operator ! — suppresses warning when you know better
string forced = middle!;   // you promise it's not null here

// Required init property — object initializer must provide a value
public class User {
    public required string Username { get; init; }
    public string? Email { get; init; }
    public string DisplayName => Email ?? Username;
}
var u = new User { Username = 'alice' };   // Email is optional

Nullable annotations inform the compiler’s analysis. The null-forgiving operator suppresses a diagnostic and does not check the value at runtime.

Refine null state with guards

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Null-conditional chaining — short-circuits on null
int? len = u.Email?.Length;
string? domain = u.Email?.Split('@').LastOrDefault();

// Null-coalescing assignment ??=
u.Email ??= 'noreply@example.com';

// Pattern-matching null check
if (u.Email is { } email) Console.WriteLine($'Email: {email}');

// Guard clauses with ArgumentNullException.ThrowIfNull (C# 10+)
public void Send(string to, string body) {
    ArgumentNullException.ThrowIfNull(to);
    ArgumentNullException.ThrowIfNull(body);
    // Compiler knows they are non-null here
}

// NotNullWhen — annotate TryParse-style methods
public bool TryGetUser(int id, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out User? user) {
    user = _store.TryGetValue(id, out var found) ? found : null;
    return user is not null;
}
if (TryGetUser(1, out var result)) {
    Console.WriteLine(result.Username);   // no warning — result is non-null here
}

Pattern tests and guards narrow the possible state. NotNullWhen communicates a guarantee tied to a boolean result.

Immutability Patterns

C# offers several immutability tools: records with with expressions for non-destructive mutation, readonly struct for stack-efficient value types, init accessors for post-construction locking, and ImmutableList<T> / ImmutableDictionary<K,V> from System.Collections.Immutable for persistent data structures.

A with expression creates a shallow copy. If a property refers to a mutable list, the original and the copy still share that list unless you replace it or use an immutable collection.

Copy records and define readonly values

csharp
// Record — value equality, immutable by default, with expression
public record Address(string Street, string City, string Country);
public record Person(string Name, int Age, Address HomeAddress);

var alice = new Person('Alice', 30, new Address('1 Main St', 'Springfield', 'US'));
var moved  = alice with { HomeAddress = alice.HomeAddress with { City = 'Shelbyville' } };
Console.WriteLine(alice == moved);   // false

// Readonly struct — value type, fully immutable, efficient in collections
public readonly struct Money(decimal Amount, string Currency) {
    public decimal Amount   { get; } = Amount;
    public string  Currency { get; } = Currency;
    public Money Add(Money other) {
        if (Currency != other.Currency) throw new InvalidOperationException('Currency mismatch');
        return new Money(Amount + other.Amount, Currency);
    }
    public override string ToString() => $'{Amount:F2} {Currency}';
}

A with expression copies a record and applies the specified member changes.

Apply persistent updates or freeze construction

csharp
// ImmutableList — persistent data structure; mutations return new instances
using System.Collections.Immutable;
var list  = ImmutableList.Create(1, 2, 3);
var list2 = list.Add(4).Add(5);     // list is unchanged
var list3 = list2.Remove(2);        // [1, 3, 4, 5]

// ImmutableDictionary
var dict  = ImmutableDictionary<string, int>.Empty;
var dict2 = dict.Add('a', 1).Add('b', 2).SetItem('a', 99);

// Builder pattern for efficient batch mutations
var builder = list.ToBuilder();
for (int i = 0; i < 1000; i++) builder.Add(i);
var large = builder.ToImmutable();   // single allocation

// Freeze pattern — mutable during construction, then locked
public class AppConfig {
    private readonly Dictionary<string, string> _settings = new();
    private bool _frozen;

    public void Set(string key, string val) {
        if (_frozen) throw new InvalidOperationException('Config is frozen');
        _settings[key] = val;
    }
    public void Freeze() => _frozen = true;
    public string Get(string key) => _settings[key];
}

// init accessor — settable only in object initializers or constructors
public class Options {
    public int Timeout  { get; init; } = 30;
    public int Retries  { get; init; } = 3;
    public bool Verbose { get; init; }
}

An immutable collection update returns a new value. A builder can group changes before publishing the immutable result.

Minimal API Patterns

Minimal APIs (.NET 6+) define HTTP endpoints as lambdas or method groups directly on WebApplication, without controller classes. Route groups share prefixes and middleware. Endpoint filters provide cross-cutting concerns like logging and validation, and built-in Results helpers return typed HTTP responses.

Use an ASP.NET Core project created with dotnet new web for the endpoint fragments.

Map endpoints and return results

csharp
// .NET 6+ Minimal API — no controllers, no startup class
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();

// Route handlers — lambda or method group
app.MapGet("/products", async (IProductRepository repo) =>
    Results.Ok(await repo.GetAllAsync()));

app.MapGet("/products/{id:int}", async (int id, IProductRepository repo) => {
    var product = await repo.FindAsync(id);
    return product is null
        ? Results.NotFound()
        : Results.Ok(product);
});

app.MapPost("/products", async (CreateProductDto dto, IProductRepository repo) => {
    var product = new Product(dto.Name, dto.Price);
    await repo.AddAsync(product);
    return Results.Created($"/products/{product.Id}", product);
});

app.MapPut("/products/{id:int}", async (int id, UpdateProductDto dto, IProductRepository repo) => {
    var existing = await repo.FindAsync(id);
    if (existing is null) return Results.NotFound();
    existing.Update(dto.Name, dto.Price);
    await repo.SaveAsync();
    return Results.NoContent();
});

app.MapDelete("/products/{id:int}", async (int id, IProductRepository repo) => {
    await repo.DeleteAsync(id);
    return Results.NoContent();
});

Route handlers bind request data and return results that determine the HTTP response.

Share a route prefix and apply filters

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Route groups (C# .NET 7+) — shared prefix + middleware
var api = app.MapGroup("/api/v1").RequireAuthorization();
api.MapGet("/me", (ClaimsPrincipal user) => Results.Ok(user.Identity?.Name));

// Filters — run before/after each endpoint in the group
api.AddEndpointFilter(async (ctx, next) => {
    Console.WriteLine($"Before: {ctx.HttpContext.Request.Path}");
    var result = await next(ctx);
    Console.WriteLine($"After: {ctx.HttpContext.Response.StatusCode}");
    return result;
});

app.Run();

record CreateProductDto(string Name, decimal Price);
record UpdateProductDto(string Name, decimal Price);

Add these registrations before running the application. The group applies its prefix and filters to its endpoints.

Best Practices

Design & Architecture

Assign components cohesive responsibilities and make collaborators explicit. Separate domain rules from transport and storage details where they have independent reasons to change.

Assign responsibilities to types

csharp
// Design & Architecture Best Practices

// SOLID: Single Responsibility — one reason to change
public class InvoiceRenderer { public string Render(Invoice i) => ...; }
public class InvoiceCalculator { public decimal Total(Invoice i) => ...; }

// SOLID: Open/Closed — extend via new types, not edits
public abstract class Discount { public abstract decimal Apply(decimal price); }
public class PercentDiscount(double pct) : Discount {
    public override decimal Apply(decimal price) => price * (decimal)(1 - pct);
}

// Prefer composition over inheritance
public class NotifyingRepository(IRepository inner, IEventBus bus) : IRepository {
    public async Task SaveAsync(Order o) { await inner.SaveAsync(o); await bus.PublishAsync(new OrderSaved(o.Id)); }
}

// Interfaces for testability
public interface ITimeProvider { DateTime UtcNow { get; } }
public class SystemTimeProvider : ITimeProvider { public DateTime UtcNow => DateTime.UtcNow; }

A small interface can expose a dependency to callers and tests. Composition lets the caller supply an implementation.

Express data and visibility in declarations

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Records for DTOs — structural equality, immutable, concise
public record CreateUserRequest(string Email, string Password, string DisplayName);

// Sealed classes for leaf types — no unintended subclassing
public sealed class EmailAddress {
    public string Value { get; }
    public EmailAddress(string v) { Value = v.Contains('@') ? v : throw new ArgumentException('Invalid email'); }
}

// internal over public by default — least privilege visibility
internal class OrderValidator { internal bool IsValid(Order o) => o.Items.Any(); }

// File-scoped namespaces — reduces indentation, one per file
namespace MyApp.Orders;

// Expression-bodied members for simple getters/computations
public class Circle(double radius) {
    public double Radius => radius;
    public double Area   => Math.PI * radius * radius;
    public double Circumference => 2 * Math.PI * radius;
}

Records express value equality. Sealed and internal declarations constrain extension and visibility respectively.

Null Safety & Defensive Coding

Nullable annotations guide compiler analysis of possible null values. They do not validate external data at runtime, so check inputs at system boundaries.

Validate required inputs

csharp
// Null Safety & Defensive Coding Best Practices

// Enable in .csproj: <Nullable>enable</Nullable>
#nullable enable

// Use ArgumentNullException.ThrowIfNull (C# 10+) at method entry
public void Process(Order order, ILogger logger) {
    ArgumentNullException.ThrowIfNull(order);
    ArgumentNullException.ThrowIfNull(logger);
    // Compiler knows both are non-null here
}

// required init for DTOs — object initializer must supply these
public class UserDto {
    public required string Id   { get; init; }
    public required string Name { get; init; }
    public string? Email        { get; init; }   // optional
}

A required property must be set during initialization. ThrowIfNull guards values that can still arrive as null at runtime.

Choose fallbacks and initialize lazily

csharp
// Use the relevant setup or declarations from the preceding fragment.
// ?. and ?? operators — safe chaining
string? raw = GetInput();
int len = raw?.Trim().Length ?? 0;
string display = raw?.ToUpper() ?? '(empty)';

// Pattern matching over null checks
if (raw is { Length: > 0 } trimmed) Console.WriteLine(trimmed);

// is not null — clearest null-guard
if (raw is not null) Console.WriteLine(raw.Length);

// Guard clauses at method entry — fail fast
public decimal Divide(decimal a, decimal b) {
    if (b == 0) throw new ArgumentException('Divisor cannot be zero', nameof(b));
    return a / b;
}

// Prefer empty collections over null — never make callers null-check
public IReadOnlyList<Order> GetOrders() => _orders ?? [];

// Null-coalescing assignment ??= — lazy init
_cache ??= new Dictionary<string, string>();

Null-conditional access short-circuits. Coalescing supplies a fallback or initializes a null variable.

Async Best Practices

Await work through the call chain and propagate supported cancellation. Blocking on tasks can waste threads and deadlock under some synchronization contexts.

Propagate tasks and cancellation

csharp
// Async Best Practices

// Always await — never fire-and-forget silently
public async Task SaveAsync(Order order) {
    await _repo.SaveAsync(order);          // awaited
    await _bus.PublishAsync(new OrderSaved(order.Id));
}

// Never async void — use async Task; except for event handlers
private async void OnButtonClick(object sender, EventArgs e) {   // OK: event handler
    await DoWorkAsync();
}

// CancellationToken everywhere — propagate, never ignore
public async Task<IReadOnlyList<Product>> SearchAsync(
    string query, CancellationToken ct = default) {
    return await _db.Products
        .Where(p => p.Name.Contains(query))
        .ToListAsync(ct);
}

// ConfigureAwait(false) in library code — avoids deadlocks, improves perf
public async Task<byte[]> ReadAllBytesAsync(string path, CancellationToken ct = default) {
    await using var stream = File.OpenRead(path);
    using var ms = new MemoryStream();
    await stream.CopyToAsync(ms, ct).ConfigureAwait(false);
    return ms.ToArray();
}

Await exposes completion and failure. Pass the caller’s cancellation token to the work it controls.

Coordinate independent asynchronous work

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Avoid blocking on async — never .Result or .Wait() from sync context
// BAD: var data = GetDataAsync().Result;
// GOOD: await GetDataAsync()

// ValueTask for hot paths that often complete synchronously
public ValueTask<int> GetCachedCountAsync() {
    if (_cache.TryGetValue('count', out int n)) return new ValueTask<int>(n);
    return new ValueTask<int>(LoadCountAsync());
}

// Task.WhenAll for parallel independent work
public async Task<(User, IList<Order>)> LoadDashboardAsync(int userId, CancellationToken ct) {
    var userTask   = _users.FindAsync(userId, ct);
    var ordersTask = _orders.GetByUserAsync(userId, ct);
    await Task.WhenAll(userTask, ordersTask);
    return (await userTask, await ordersTask);
}

Start independent tasks before awaiting WhenAll. Await lets the caller suspend without blocking the current thread.

LINQ & Collections

Keep queries readable and materialize deliberately. A snapshot avoids repeated enumeration when callers require stable results rather than a live traversal.

Control when a sequence is evaluated

csharp
// LINQ & Collections Best Practices

// Prefer LINQ for clarity over manual loops
var expensiveTools = products
    .Where(p => p.Category == 'Tools' && p.Price > 50)
    .OrderBy(p => p.Name)
    .Select(p => p.Name)
    .ToList();

// Avoid multiple enumeration — materialize IEnumerable once
IEnumerable<Order> orders = GetOrders();
var list = orders.ToList();           // single enumeration
var count = list.Count;
var first = list.FirstOrDefault();

// ToList() / ToArray() to materialize and avoid deferred execution surprises
var names = _db.Users.Where(u => u.IsActive).Select(u => u.Name).ToArray();

Materialize a sequence when later consumers need a snapshot or would otherwise repeat costly enumeration.

Choose storage for frequent queries

csharp
// Use the relevant setup or declarations from the preceding fragment.
// HashSet for O(1) membership tests
var allowedIds = new HashSet<int> { 1, 2, 3, 42 };
var filtered   = items.Where(i => allowedIds.Contains(i.Id)).ToList();

// Dictionary for O(1) lookups
var byId = products.ToDictionary(p => p.Id);
if (byId.TryGetValue(targetId, out var product)) Console.WriteLine(product.Name);

// ImmutableArray for read-only data shared across threads
public static readonly ImmutableArray<string> AllowedRoles =
    ['admin', 'editor', 'viewer'];

// IEnumerable in signatures when you only iterate; List/IReadOnlyList when count needed
public IEnumerable<string> GetNames() => _items.Select(i => i.Name);
public IReadOnlyList<Order> GetOrders() => _orders.AsReadOnly();

// Avoid LINQ in hot paths — manual loops are faster for tight inner loops
for (int i = 0; i < buffer.Length; i++) {
    if (buffer[i] == 0) count++;
}

Use a set for repeated membership checks and a dictionary for repeated key lookups.

Exception Handling

Preserve stack traces and catch only failures the current layer can handle. Cleanup belongs in using or finally paths so it runs for either outcome.

Catch failures the caller can handle

csharp
// Exception Handling Best Practices

// Only catch what you can actually handle
try {
    var data = await _client.GetStringAsync(url, ct);
    return JsonSerializer.Deserialize<ApiResponse>(data);
} catch (HttpRequestException ex) {
    _logger.LogWarning(ex, 'HTTP request to {Url} failed', url);
    return null;   // caller handles null — we handled what we could
}

// Use specific exception types, not base Exception
public class OrderNotFoundException : Exception {
    public int OrderId { get; }
    public OrderNotFoundException(int id)
        : base($'Order {id} not found') => OrderId = id;
    public OrderNotFoundException(int id, Exception inner)
        : base($'Order {id} not found', inner) => OrderId = id;
    protected OrderNotFoundException(
        System.Runtime.Serialization.SerializationInfo info,
        System.Runtime.Serialization.StreamingContext ctx) : base(info, ctx) { }
}

Catch a specific exception when the handler can recover or translate it to an application result.

Filter, report and preserve failures

csharp
// Use the relevant setup or declarations from the preceding fragment.
// Never swallow exceptions silently
// BAD: catch (Exception) { }
// GOOD: log, rethrow, or convert to domain error

// Log before rethrowing or converting
try { await _db.SaveChangesAsync(ct); }
catch (DbUpdateException ex) {
    _logger.LogError(ex, 'Failed to persist order {Id}', order.Id);
    throw new OrderPersistenceException('Could not save order', ex);
}

// when clause — filter without catching
try { await ProcessAsync(); }
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests) {
    await Task.Delay(TimeSpan.FromSeconds(5), ct);
    await ProcessAsync();
}

// ExceptionDispatchInfo — rethrow without losing original stack trace
ExceptionDispatchInfo? captured = null;
try { await RiskyAsync(); }
catch (Exception ex) { captured = ExceptionDispatchInfo.Capture(ex); }
if (captured is not null) captured.Throw();

A filter checks whether a handler applies. Rethrowing or using ExceptionDispatchInfo preserves the original stack context.

Performance & Memory

Measure allocation and execution costs before optimizing. Pools and span-based APIs can reduce copying but introduce lifetime and ownership constraints.

Reuse and slice temporary storage

csharp
// Performance & Memory Best Practices

// Span<T> / Memory<T> for buffer work — zero allocation slicing
public int CountNewlines(ReadOnlySpan<char> text) {
    int count = 0;
    foreach (char c in text) if (c == '
') count++;
    return count;
}
CountNewlines(largeString.AsSpan(offset, length));   // no allocation

// readonly struct for small value types — no defensive copies, no heap alloc
public readonly struct Color(byte r, byte g, byte b) {
    public byte R { get; } = r;
    public byte G { get; } = g;
    public byte B { get; } = b;
    public int ToArgb() => (R << 16) | (G << 8) | B;
}

// ArrayPool — reuse temp arrays, avoid GC pressure
var pool = System.Buffers.ArrayPool<byte>.Shared;
byte[] buf = pool.Rent(4096);
try { /* use buf */ }
finally { pool.Return(buf); }

A span views an existing buffer. A pooled array can be reused when the caller returns it after use.

Reduce text allocations and boxing

csharp
// Use the relevant setup or declarations from the preceding fragment.
// StringBuilder for string concatenation in loops
var sb = new System.Text.StringBuilder();
foreach (var line in lines) sb.AppendLine(line);
string result = sb.ToString();

// StringComparison.Ordinal for perf-sensitive string ops
if (string.Equals(a, b, StringComparison.Ordinal)) { }
int idx = text.IndexOf('prefix', StringComparison.Ordinal);

// Avoid boxing value types — use generics instead of object
// BAD: object boxed = 42;  IEnumerable<object> ints = new[] { (object)1, (object)2 };
// GOOD:
void Print<T>(T value) where T : struct => Console.WriteLine(value);

// Minimize allocations in hot paths — measure with BenchmarkDotNet
// [MemoryDiagnoser] on benchmark class shows Gen0/Gen1/Gen2 allocs

// dotMemory / PerfView / ETW for production profiling
// BenchmarkDotNet for micro-benchmarks — never guess, always measure

A StringBuilder accumulates text across iterations, and generic operations can keep value types unboxed. Measure both in the target workload.

Diagram
100%