Volume 1 · Chapter 4 — Modern C# and .NET Foundations
Advanced C# Language Features
4.1 Introduction
Modern C# has grown from a straightforward object-oriented language into a powerful, multi-paradigm one supporting functional style, high-performance memory access, rich pattern matching, and expressive domain modeling. A senior engineer needs more than syntax: you need to understand how each feature behaves at runtime and what it costs, so you can use it where it improves clarity, safety, or performance and avoid it where it adds ceremony. This chapter surveys the features that most shape enterprise code.
4.2 Generics
Generics let you write reusable, type-safe components without casting or boxing. Before generics, reusable containers usedobject, which required casts and risked runtime errors; generics give compile-time type safety and let the runtime generate optimized code specialized for value types.
public class Repository<T> where T : class
{
private readonly List<T> _items = new();
public void Add(T entity) => _items.Add(entity); // type-safe, no boxing, no casts
public IReadOnlyList<T> All => _items;
}
4.3 Delegates and Events
A delegate is a type-safe reference to a method - the basis of callbacks, functional composition, LINQ, and events. Aneventis a controlled publisher-subscriber wrapper over a delegate that prevents external code from invoking or overwriting the subscriber list, only subscribing and unsubscribing.
public delegate void NotificationHandler(string message);
public sealed class PaymentService
{
public event EventHandler<decimal>? PaymentCompleted; // controlled pub/sub
public void Complete(decimal amount) => PaymentCompleted?.Invoke(this, amount);
}
Events are the mechanism behind domain-event notifications, UI updates, and message processing - but remember (Volume 7) that an event holds a reference to every subscriber, so subscribers must unsubscribe to avoid leaks.
4.4 Lambdas, LINQ, and Deferred Execution
Lambda expressions provide concise anonymous functions, used heavily in LINQ and configuration. LINQ offers a unified query model over collections and data sources. A critical behavior isdeferred execution: many LINQ queries are not run when defined but when enumerated, which affects correctness (the underlying data may change) and performance (re-enumeration re-runs the whole query).
var activeCustomers = customers.Where(c => c.IsActive); // NOT executed yet (deferred)
int count = activeCustomers.Count(); // executes here
var list = activeCustomers.ToList(); // executes AGAIN - re-enumerates
4.5 Expression Trees
Expression trees represent code as data that can be inspected and transformed at runtime. This is how EF Core translates a LINQ query into SQL - it walks the expression tree rather than executing the lambda - and it underpins many frameworks.
Expression<Func<Customer, bool>> filter = c => c.IsActive; // code as data
// EF Core inspects this tree and emits: WHERE IsActive = 1
4.6 Records, Pattern Matching, and Nullable Reference Types
Recordsgive immutable data types with value-based equality and non-destructive mutation - ideal for DTOs, messages, and value objects.Pattern matchingexpresses branching declaratively and often exhaustively.Nullable reference typesmove null-safety to compile time, turning manyNullReferenceExceptions into build warnings.
public record Customer(int Id, string Name); // immutable, value equality
decimal Discount(Customer c) => c switch // pattern matching
{
PremiumCustomer => 0.10m,
{ Name: "" } => throw new ArgumentException("name required"),
_ => 0m
};
#nullable enable
string? maybeNull = null; // compiler tracks nullability and warns on unsafe use
4.7 Span and Memory
Span<T>andMemory<T>give safe, allocation-free views over arrays, stack memory, and strings, enabling high-performance parsing and buffer handling without copies - crucial in APIs, serializers, and networking (covered in depth in Volume 7).
Span<byte> buffer = stackalloc byte[1024]; // stack-allocated, zero heap allocation
// slice and process without copying:
Span<byte> header = buffer[..16];
Why are generics more efficient than using object?
Because generics avoid the boxing and casting thatobject-based code requires, and they let the runtime generate specialized code. When you store value types in anobject-based container, each is boxed (a heap allocation and copy) and must be cast back out (with a runtime type check that can fail), which costs performance and safety. A generic container parameterized on the value type stores it directly with no boxing and no cast, and the JIT generates a specialized implementation for each value type (reference types share one implementation), so you get compile-time type safety, no allocations from boxing, and no runtime cast failures. Generics also make code reusable across types without duplication. So compared with the oldobject/ArrayListapproach, generics are both safer (errors caught at compile time) and faster (no boxing, no casts), which is why generic collections replaced the non-generic ones for virtually all code.
What is deferred execution in LINQ, and why does it matter?
Deferred execution means a LINQ query is not run when it is defined but when its results are actually enumerated - the query is stored as an expression (or an iterator) and executed lazily on iteration or materialization (ToList,Count,foreach). It matters for two reasons. Correctness: because the query runs when enumerated, it sees the state of the underlying data at that moment, so if the source changes between defining and enumerating the query, you get the newer data - which can be surprising. And it means a query can capture variables that change. Performance: because execution is deferred, enumerating the same query variable multiple times re-executes the entire query each time (re-querying the database or re-iterating the collection), which is a common, costly mistake - the fix is to materialize once withToListand reuse the list. Deferred execution is also what enables composability (building a query in stages) and, against a database, lets the full query be translated to a single SQL statement executed once. So I use it deliberately: compose queries lazily, but materialize before multiple enumerations, and be aware the query reflects data at enumeration time.
What are expression trees and where are they used?
Expression trees represent code as a traversable data structure rather than as compiled, executable code - anExpression<Func<...>>is a tree of nodes describing the operations (a property access, a comparison, a method call) instead of a delegate you simply invoke. This lets frameworks inspect and transform the code at runtime. The canonical use is Entity Framework Core (and other ORMs/LINQ providers): when you write a LINQ query againstIQueryable, the lambda is captured as an expression tree, and EF Core walks that tree to translate the query into SQL, rather than running the lambda in memory - which is whyIQueryablequeries execute in the database whileIEnumerablequeries execute in memory. Expression trees also power dynamic query building, some mapping and validation frameworks, and high-performance scenarios where you compile an expression tree into a fast delegate at runtime (a faster alternative to reflection). The key insight is that expression trees turn code into data that can be analyzed and translated, which is the mechanism behind LINQ-to-SQL-style providers - and understanding this explains why a query that can be translated behaves very differently from one that falls back to in-memory evaluation.
Why prefer records and immutability for DTOs, events, and value objects?
Because immutability removes an entire class of bugs from shared mutable state and records make it concise. An immutable object cannot change after construction, so it is inherently thread-safe (shareable across threads without locks or defensive copies) and cannot be mutated unexpectedly by distant code, which makes behavior far easier to reason about in a large system. Records add two things that suit these use cases perfectly: value-based equality, so two records with the same data are equal - exactly what you want for DTOs, messages, events, and value objects like Money - and non-destructive mutation withwith, so you create a modified copy instead of mutating in place. DTOs and API/event contracts benefit because they are data carriers that should not be accidentally mutated as they flow through the system, and value objects benefit because their identityistheir value. 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 hot paths where copying cost matters. In short, records give thread-safe, predictable, value-equal data types in one line, which is why they are the modern default for DTOs, events, and value objects.
4.8 Production Scenario
A high-volume payment API suffers excessive allocations during message processing - profiling shows unnecessary string creation and array copying on the hot path. The team rewrites the parser usingSpan<T>to slice buffers without allocating substrings, models the messages as immutable records, and switches to source-generated serialization - dramatically cutting allocations and GC pressure without changing the API contract.
Chapter Revision Notes
- Generics give type-safe reuse without boxing or casting.
- Events are controlled pub/sub over delegates - unsubscribe to avoid leaks.
- LINQ uses deferred execution - materialize once before multiple enumerations.
- Expression trees turn code into data - the basis of EF Core’s SQL translation.
- Records give immutable, value-equal types; nullable reference types catch nulls at compile time.
- Span/Memory enable allocation-free, high-performance memory access.