C#
Records & Pattern Matching
6 question(s)
What is a record and how does it differ from a class?
Beginner
A record is a reference type with compiler-generated value equality, ToString and non-destructive mutation (with). It's ideal for immutable data.
public record Person(string Name, int Age);
var p2 = p1 with { Age = 31 };
Real-world example
DTOs and value objects use records so equality and copying just work.
What does the with expression do?
Beginner
with creates a copy of a record with some properties changed, leaving the original unchanged (non-destructive mutation).
var updated = order with { Status = "Shipped" };
Real-world example
Producing a new immutable state object from the previous one in a reducer/state store.
What is a record struct and when would you use it?
Intermediate
A record struct is a value type with record-like value semantics and equality; use it for small immutable value data where you also want stack/value copying.
public readonly record struct Point(int X, int Y);
Real-world example
Coordinates or money where value equality plus no heap allocation is desirable.
How does switch pattern matching improve code?
Intermediate
switch expressions match on type, constant, relational and property patterns, returning a value concisely and forcing exhaustive, readable branching.
string Size(int n) => n switch { < 10 => "small", < 100 => "medium", _ => "large" };
Real-world example
Mapping an HTTP status or an enum to a message without long if/else chains.
What are property and positional patterns useful for?
Advanced
They deconstruct and test an object's shape in one expression, enabling clear rules over complex data without manual null checks and casts.
var label = point switch { (0,0) => "origin", ( >0, >0) => "Q1", _ => "other" };
Real-world example
Routing a domain event by its type and fields in one expressive switch.
When should you NOT use records?
Advanced
For entities with identity and mutable state (like EF Core aggregates), where value equality and immutability are wrong; use classes there. Records suit values, not entities.
public class Order { public int Id { get; set; } public string Status { get; set; } }
Real-world example
An EF Core entity tracked by Id stays a class; a money value object becomes a record.