CS Fundamentals Trainer · Guides
Modern C# data modelling: records, immutability and nullable reference types
What a record gives you (value equality, with-expressions, deconstruction), record class against record struct against class, init-only and required members, what nullable reference types really check and what they do not, and how pattern matching ties them together.
4 min read
Two language features changed how C# code models data: records (C# 9 and later) for immutable data with value semantics, and nullable reference types (C# 8 and later) for making "can this be null" part of the type. They work well together.
Records
A record is a class (or struct) whose compiler-generated members are built around its data.
public record Point(int X, int Y); // positional record: an immutable class
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b); // True (value equality, not reference)
var c = a with { Y = 5 }; // copy with one change; a is unchanged
var (x, y) = c; // deconstruction
Console.WriteLine(a); // Point { X = 1, Y = 2 }
The compiler generates Equals/GetHashCode over all fields, ==/!=, a readable ToString, a Deconstruct method and the copy used by with. The positional form makes the properties init-only, so they can be set while the object is being created and never after.
Which to use
| Equality | Copy semantics | Typical use | |
|---|---|---|---|
class | reference | shared reference | entities with identity and lifecycle |
record (record class) | by value | shared reference, immutable by default | DTOs, messages, value objects |
struct / record struct | by value | copied on assignment | small, short-lived values |
Careful with value equality on mutable members: a record that holds a List<int> compares the list by reference, so two "equal-looking" records can differ. Records are not a good fit for entities that EF Core tracks by identity.
Init-only and required members
public class Customer
{
public required string Name { get; init; } // C# 11: the caller must set it
public string? Phone { get; init; } // optional
}
var c = new Customer { Name = "Ana" }; // c.Name = "x" later would not compile
init allows setting in an object initializer or constructor only; required makes the compiler reject object creation that forgets the member. Together they give you immutable, always-valid objects without a long constructor.
Immutability
Immutable data is simple to reason about, can be shared between threads without locks and can be used as dictionary keys. The costs are copies when you change a field (with allocates a new object) and awkward deep updates. Use it by default for data that is passed around, and keep mutation inside small, local scopes. For collections, IReadOnlyList<T> hides mutation, while ImmutableArray<T> and ImmutableDictionary<TKey,TValue> really prevent it.
Nullable reference types
With <Nullable>enable</Nullable> in the project file, every reference type is non-nullable by default. string means "never null"; string? means "may be null". The compiler then performs flow analysis and warns when a possibly-null value is dereferenced or when null is assigned to a non-nullable one.
string? input = GetInput();
Console.WriteLine(input.Length); // warning CS8602: dereference of a possibly null reference
if (input is not null) Console.WriteLine(input.Length); // fine: the compiler knows
What it is: a compile-time annotation and warning system. What it is not: a runtime guarantee. Nothing stops null from arriving through reflection, deserialisation, unannotated libraries, or code with the feature off. Validate data at the boundaries (public APIs, deserialised input) with ArgumentNullException.ThrowIfNull(x), and treat the warnings as errors in new projects (<TreatWarningsAsErrors> or WarningsAsErrors for nullable).
Useful pieces:
x!(the null-forgiving operator) tells the compiler "trust me". Every use is a place the program can fail, so use it rarely and with a reason.?.and??short-circuit and default:name?.Trim() ?? "unknown".- Attributes such as
[NotNullWhen(true)](as inTryGetValue) and[MemberNotNull]teach the analyser about your methods. - Value types are different:
int?isNullable<int>, a real runtime type.
Pattern matching
Records and nullability pair with patterns, which test shape and null together:
string Describe(object? o) => o switch
{
null => "nothing",
Point { X: 0, Y: 0 } => "origin",
Point(var x, _) when x < 0 => "left half",
Point => "a point",
string s => $"text of {s.Length}",
_ => "something else",
};
A switch expression must cover all inputs, and the compiler warns when a case is missing, which is a good reason to model alternatives as a small hierarchy of records and match over them.
Sources
- Microsoft Learn: Records.
- Microsoft Learn: Nullable reference types.
- Microsoft Learn: Pattern matching.
Practise this topic: C# & .NET