Part 1 · 1 chapters · ~8 min
The Type System
Value and reference types, structs and classes measured, records and record structs, nullable reference types and annotations, generics with constraints and reification, interfaces with default and static abstract members, sealed hierarchies and pattern matching, Span<T>, and boxing.
2
Values, references and nulls
code
readonly record struct Kobo(long Value) { public static Kobo operator +(Kobo a, Kobo b) => new(a.Value + b.Value); }
public readonly record struct AccountId(string Value);
#nullable enable
string? preferred = user.PreferredName;
string shown = preferred?.Trim() is { Length: > 0 } p ? p : user.FullName; // property pattern + null check
abstract record Payout(string Id);
sealed record Pending(string Id) : Payout(Id);
sealed record Settled(string Id, string RailRef) : Payout(Id);
sealed record Failed(string Id, string Reason) : Payout(Id);
static string Label(Payout p) => p switch { Pending => "Processing", Settled s => $"Sent ({s.RailRef})", Failed f => $"Failed: {f.Reason}", _ => throw new UnreachableException() };
// measured: 10M class instances 29 ms / 240 MB allocated · 10M structs 5 ms / 0 MBGenerics are reified in .NET: List<int> stores real ints, unlike Java's erased generics, which store boxed Integers (Programming Languages P2).
VALUE TYPES VS REFERENCE TYPES, MEASURED
.NET 10.0.12, Release, Apple M3 Pro: 10,000,000 Money values
swipe the figure sideways, or tap expand for full screen
1/4
reference types
A class instance lives on the heap with an object header: 10 million small Money objects allocated 240 MB in total and took 29 ms, creating work for the garbage collector.
heap objects: 240 MBGC pressure