Volume 10 · Chapter 2 — Advanced .NET Engineering, Modern Development & AI-Assisted Software Engineering
Advanced C# Programming Patterns
2.1 Introduction
Modern C# has evolved into a language that lets you express intent concisely and safely - immutable data with records, exhaustive branching with pattern matching, compile-time null safety with nullable reference types, and low-allocation code withSpanand source generators. Using these features well is not about chasing novelty; each one removes a class of bugs or overhead that plagued older code. This chapter surveys the features that most improve enterprise code quality and performance.
2.2 Records and Immutability
Records give you immutable types with value-based equality and non-destructive mutation (with) in a single line. They are ideal for DTOs, messages, events, and value objects, where immutability eliminates whole categories of shared-mutable-state bugs and makes code safe to share across threads.
public sealed record Money(decimal Amount, string Currency)
{
public Money Add(Money other) => this with { Amount = Amount + other.Amount };
}
var a = new Money(100, "USD");
var b = a with { Amount = 150 }; // new instance; 'a' is unchanged
bool same = a == new Money(100, "USD"); // true - value equality
2.3 Pattern Matching
Pattern matching turns sprawlingif/elseand type-check chains into readable, often exhaustive, switch expressions. Type, property, relational, and list patterns let you branch on the shape of data declaratively.
decimal Fee(Transaction t) => t switch
{
{ Amount: <= 0 } => throw new ArgumentException(),
{ Type: TxType.Wire, Amount: > 10000 } => t.Amount * 0.001m,
{ Type: TxType.Wire } => 15m,
{ Type: TxType.Internal } => 0m,
_ => 5m
};
2.4 Nullable Reference Types
Nullable reference types move null-safety to compile time: the compiler tracks which references may be null and warns when you dereference them unsafely, turning the “billion-dollar mistake” ofNullReferenceExceptioninto a build-time diagnostic. Enabling<Nullable>enable</Nullable>across a codebase is one of the highest-value modernization steps.
2.5 Generics and Constraints
Generics provide reuse without boxing or loss of type safety, and constraints let you require capabilities (a base type, an interface, a parameterless constructor). Modern C# adds generic math via static abstract interface members, enabling algorithms that work over any numeric type.
2.6 Span, Memory, and Low-Allocation Code
Span<T>andMemory<T>give safe, allocation-free views over arrays, stack memory, and strings, enabling high-performance parsing and buffer handling without copies. Combined withstackallocand pooling, they let hot paths avoid the GC pressure discussed in Volume 7.
// Parse a fixed-format record with zero heap allocations.
static (int account, decimal amount) Parse(ReadOnlySpan<char> line)
{
int comma = line.IndexOf(',');
int account = int.Parse(line[..comma]);
decimal amount = decimal.Parse(line[(comma + 1)..]);
return (account, amount); // no substrings allocated
}
2.7 Async Streams and ValueTask
IAsyncEnumerable<T>withawait foreachlets you stream asynchronous sequences (paged API results, database cursors) without buffering everything in memory.ValueTaskavoids allocating aTaskfor the common case where an async method completes synchronously (a cache hit), reducing allocations on hot paths.
2.8 Source Generators over Reflection
Source generators run at compile time to emit code, replacing runtime reflection with generated, AOT-friendly, zero-startup-cost code. System.Text.Json’s source generator andLoggerMessageare prime examples: faster, trimmable, and analyzable at build time. Preferring source generators to reflection is a modern performance and AOT-readiness pattern.
Why prefer immutable objects (records) in enterprise applications?
Immutability removes an entire class of bugs rooted in shared mutable state. An immutable object cannot be changed after creation, so it is inherently thread-safe - you can share it across threads without locks or defensive copies - and it cannot be mutated unexpectedly by faraway code, which makes behavior far easier to reason about in a large system. Records make this cheap in C#: they give value-based equality (two records with the same data are equal, ideal for DTOs, events, and value objects) and non-destructive mutation withwith(create a modified copy instead of mutating). This suits domain value objects like Money, message and event contracts, and DTOs, where accidental mutation or aliasing would be a subtle, dangerous bug. The trade-off is more allocation when you copy frequently, so I use immutability by default for data-carrying types and reserve mutability for entities with genuine lifecycle and for performance-critical hot paths.
What do nullable reference types give you, and what are their limits?
They move null-safety from a runtime failure to a compile-time diagnostic. With the feature enabled, the compiler tracks whether each reference is intended to be nullable (string?) or not (string) and warns when you might dereference a possibly-null value or assign null to a non-nullable one - catching the classicNullReferenceExceptionbefore it ships and documenting intent in the type signatures. The limits are important to state honestly: it is a compile-time, opt-in analysis, not a runtime guarantee, so nulls can still arrive from code that did not enable it, from deserialization, reflection, or interop, and the compiler’s flow analysis can be defeated or suppressed. So it dramatically reduces null bugs and improves API clarity, but you still validate inputs at trust boundaries. Enabling it across a codebase is one of the highest-value, relatively low-cost modernization steps precisely because it surfaces latent null bugs at build time.
When would you use ValueTask instead of Task, and what is the risk?
I useValueTaskorValueTask<T>on hot async paths that frequently complete synchronously, to avoid allocating aTaskobject each call - the canonical case being a cache lookup that usually hits (returns immediately) and only occasionally misses (goes async). Avoiding that allocation matters when the method is called millions of times. The risk is thatValueTaskhas stricter usage rules thanTask: it must not be awaited more than once, must not be awaited concurrently, and its result must not be accessed before completion - violating these causes subtle, hard-to-diagnose bugs. So I reach for it only where profiling shows the allocation matters, keep its usage simple (await it exactly once immediately), and use plainTaskeverywhere else, where its flexibility and familiarity outweigh a negligible allocation. It is a targeted micro-optimization, not a default.
Why prefer source generators over reflection in modern .NET?
Because source generators do at compile time what reflection does at runtime, with better performance, startup, and tooling. Runtime reflection - used by many serializers, DI containers, and mappers - inspects types dynamically, which costs CPU on first use (reflection and dynamic code generation), adds startup latency, defeats trimming (the linker cannot tell which types are used), and is incompatible with Native AOT. A source generator instead emits the equivalent code during the build, so there is no runtime reflection cost, startup is faster, the emitted code is trimmable and AOT-compatible, and you can inspect and debug the generated source. System.Text.Json’s source generator andLoggerMessageare examples that are both faster and AOT-ready. The trade-off is more build-time complexity and less runtime flexibility, but for performance-sensitive and AOT-targeted applications, replacing reflection with source generation is a clear modern best practice.
How do you drive adoption of modern C# features across a large legacy codebase without destabilizing it?
I treat it as incremental, value-driven modernization rather than a rewrite, prioritizing features by risk-reduction per unit of effort. Nullable reference types come first because they surface latent null bugs at compile time and can be enabled file-by-file or project-by-project with warnings, so teams adopt them gradually without a big-bang change. Records and pattern matching get introduced in new code and during natural refactors of DTOs, value objects, and branching logic, improving clarity without forcing sweeping edits. Performance features likeSpan, pooling, and source generators are applied surgically to measured hot paths, not everywhere, because they add complexity that is only justified where profiling shows a benefit. I back the effort with enabling infrastructure - analyzers and editorconfig rules that guide the team toward the modern idioms, updated code review standards, and shared examples - and I rely on a strong test suite so refactors are safe. I sequence it so each step is independently shippable and reversible, delivering value (fewer null bugs, clearer code, faster hot paths) continuously rather than gating on a massive migration. The principle is to modernize where it reduces real bugs or measured cost, make the modern path the default via tooling, and never destabilize working code for the sake of using a new feature.
2.9 Banking Enterprise Scenario
A bank’s payments service models Money and transaction events as immutable records with value equality, eliminating a class of aliasing bugs and making them safe to pass across threads and into the event pipeline. Fee calculation is a single exhaustive switch expression over transaction shape, replacing a tangle of conditionals. Nullable reference types, enabled across the solution, caught dozens of latent null dereferences during migration. The high-throughput statement parser usesSpanto avoid allocations, and JSON serialization uses the source generator for speed and AOT-readiness - modern C# applied where each feature removes a real bug or cost.
Chapter Revision Notes
- Records give immutable, value-equal types - ideal for DTOs, events, and value objects.
- Pattern matching expresses branching declaratively and often exhaustively.
- Nullable reference types catch null bugs at compile time (opt-in, not a runtime guarantee).
- Span/Memory and ValueTask cut allocations on measured hot paths.
- Prefer source generators to reflection for speed, startup, trimming, and AOT.
- Adopt modern features incrementally where they reduce real bugs or cost.