Library

Volume 3 · .NET & C# Deep Dive

Notebook
Sign in

Section 4

Modern C# Features (Records, Pattern Matching, Nullable Reference Types, init-only setters)

954 words · about 4 min

4.1 Records

// Records — immutable data types with value equality
public record OrderSummary(int Id, decimal Total, DateTime CreatedAt);

var a = new OrderSummary(1, 100m, DateTime.Now);
var b = a with { Total = 200m }; // Non-destructive mutation — creates a new instance

Console.WriteLine(a == b); // False — value equality compares all properties
Console.WriteLine(a.Total); // 100 — 'a' is untouched by 'with'

// Record structs (C# 10+) — value-type records, avoid heap allocation
public readonly record struct Money(decimal Amount, string Currency);

In Domain-Driven Design, records are the natural fit for Value Objects (an Address, a Currency amount): immutability and structural equality come for free instead of hand-writing overrides for Equals/GetHashCode and private setters.

4.2 Pattern Matching

public decimal CalculateShipping(Order order) => order switch
{
    { Total: > 100, Priority: true } => 0m,       // Free priority shipping
    { Total: > 100 } => 5m,                        // Discounted
    { Weight: > 50 } => order.Weight * 2m,          // Heavy items
    { Destination.Country: "US" } => 10m,           // Domestic
    _ => 25m                                        // International default
};

// Type patterns + list patterns (C# 11+)
static string Describe(object obj) => obj switch
{
    int n when n < 0 => "negative int",
    int n => $"int: {n}",
    string { Length: 0 } => "empty string",
    string s => $"string: {s}",
    int[] [1, 2, ..] => "array starting with 1, 2",
    null => "null",
    _ => "unknown"
};

4.3 Nullable Reference Types

#nullable enable
public class CustomerService
{
    public Customer? FindById(int id) => _repo.Find(id); // Explicitly nullable

    public string GetDisplayName(Customer? customer)
        => customer?.Name ?? "Unknown";
}

Nullable Reference Types (NRT) are a compile-time-only annotation/warning system — Customer? vs Customer documents intent to the compiler and to other developers, and the compiler flags likely null-dereference paths with warnings. It does not insert runtime null checks; a mis-annotated API or a suppressed warning (!) can still NullReferenceException at runtime. NRT’s real value is turning “is this ever null?” from a tribal-knowledge question into something visible in the type signature and enforced (as warnings, optionally as errors) at compile time.

4.4 Init-Only Setters, Required Members, Raw Strings

// init-only setters — settable only during object initialization
public class Config
{
    public string ConnectionString { get; init; } = string.Empty;
    public int MaxRetries { get; init; } = 3;
}
var config = new Config { ConnectionString = "...", MaxRetries = 5 };
// config.MaxRetries = 10; // Compile error — init-only after construction

// Required Members (C# 11)
public class Settings
{
    public required string ConnectionString { get; init; }
    public required int MaxRetries { get; init; }
}
// var s = new Settings(); // Compile error — required members not set

// Raw String Literals (C# 11)
var json = """
    {
        "name": "example",
        "role": "Architect"
    }
    """;

// Primary constructors (C# 12) and collection expressions (C# 12)
public class OrderService(ILogger<OrderService> logger, IOrderRepository repo)
{
    public async Task<Order?> GetAsync(int id) => await repo.FindAsync(id);
}
int[] nums = [1, 2, 3];

Interview Q&A — Section 4

Q1: Why do you use C# records for DDD Value Objects instead of ordinary classes?

A: Value Objects must be immutable and compared by value, not identity. A record gives structural equality (Equals/GetHashCode generated from all properties) and immutability by default, plus the with expression for non-destructive updates — all without hand-writing boilerplate. This keeps the domain model clean, thread-safe, and less error-prone than a class with manually implemented equality and private setters.

Q2: Do Nullable Reference Types prevent NullReferenceException at runtime?

A: No — NRT is a compile-time static-analysis feature. It annotates whether a reference type is expected to be nullable (Customer?) or non-nullable (Customer), and the compiler emits warnings for code paths that look unsafe. It doesn’t insert any runtime checks, so a suppressed warning (the ! null-forgiving operator), an external API lying about its nullability, or a warning treated as non-fatal can still produce a NullReferenceException at runtime. Its value is turning nullability into a visible, compiler-checked contract rather than undocumented tribal knowledge.

Q3: What’s the difference between init and required members, and how do they combine?

A: init makes a property settable only during object initialization (constructor or object initializer), giving you immutability after construction without needing a constructor parameter for every property. required (C# 11) forces callers to set that property during initialization — the compiler errors if it’s omitted. Combined, public required string Name { get; init; } gives you a property that must be set once, at construction time, and never again — ideal for configuration objects and DTOs where partially-initialized instances are a bug waiting to happen.

Q4: How does pattern matching in C# switch expressions improve on traditional if/else chains for domain logic?

A: Property patterns ({ Total: > 100, Priority: true }) let you express multi-condition branching declaratively and exhaustively, with the compiler warning on non-exhaustive matches (missing discard case) in many scenarios. It reads closer to a decision table than nested conditionals, and combined with sealed class hierarchies, the compiler can actually enforce that all subtypes are handled — catching a missed case at compile time instead of a runtime default-branch surprise.