Advanced C#: Pattern Matching and Source Generators
On this page
Learning Objective
Use delegates, pattern matching and generic constraints to write expressive and safe C#, explain what source generators replace, apply the built-in generators for JSON, logging and regular expressions, and avoid the security traps of reflection-heavy and backtracking code.
Concept Explanation
The C# you learned in Phase 1 was enough to build an API. The features in this lesson are the ones that make code shorter and safer once the codebase grows. Delegates are typed references to methods, and Func and Action are the general-purpose versions you already use in LINQ and in middleware, where each step receives the next step as a delegate. Lambdas capture variables, and a lambda that captures a variable keeps it alive, which is a common cause of memory held longer than expected and of subtle bugs when the captured value changes. Events are a pattern built on delegates, but in server code, explicit interfaces and dependency injection are usually clearer than events, which are easy to forget to unsubscribe.
Pattern matching is where modern C# earns its reputation. A switch expression maps input shapes to results, property patterns test parts of an object, relational patterns test ranges, and list patterns match the structure of arrays. Combined with sealed record hierarchies, the compiler can warn when a case is missing, so adding a new member of a hierarchy shows you every place that must handle it. This is far safer than a chain of if statements for things such as state transitions, authorization decisions, and mapping domain errors to HTTP results, where a forgotten case is a bug or a security hole. Generics with constraints, such as where T : IEntity or the newer static abstract interface members, let you write reusable code that stays type safe without casting. C# 14, which ships with .NET 10, adds extension members and the field keyword for properties, continuing the trend toward less boilerplate.
Source generators run at compile time and emit C# code, replacing work that used to happen at run time through reflection. The benefits are speed, no runtime code generation, and compatibility with trimming and Native AOT, which you will meet on Day 113. Three are worth using immediately. System.Text.Json can generate its serialization code through a JsonSerializerContext. The LoggerMessage attribute generates high-performance logging methods with structured parameters, which also makes it harder to log the wrong thing by accident. And GeneratedRegex produces the matching code for a regular expression at build time.
These features also have security implications. Regular expressions with nested quantifiers can take exponential time on crafted input, called catastrophic backtracking, so any regex that runs on user input needs a match timeout or the NonBacktracking option, and the generated regex accepts both. Reflection-based deserialization of arbitrary type names has been a long source of remote code execution: BinaryFormatter is dangerous enough that its implementation was removed in .NET 9, and Newtonsoft.Json's TypeNameHandling should never be enabled for untrusted input. Prefer System.Text.Json with explicit types, and when you need polymorphism, use its explicit type discriminators with a fixed list of allowed derived types.
| Feature | What it gives you | Watch for |
|---|---|---|
| Delegates, Func, Action | Behavior passed as data | Captured variables keeping objects alive |
| Switch expressions and patterns | Exhaustive, readable branching | Missing cases; use sealed hierarchies to get warnings |
| Generic constraints | Reusable code that stays type safe | Over-abstracting; prefer concrete code until repetition appears |
| Source generators | Compile-time code, no reflection | Generated code is still your responsibility to configure |
| GeneratedRegex | Fast, AOT-friendly regular expressions | Set a timeout or NonBacktracking for untrusted input |
| Polymorphic deserialization | Flexible payloads | Never deserialize arbitrary types from untrusted data |
Worked Example: Exhaustive Patterns, Generated JSON, Logging and a Safe Regex
The first block models a workflow with a sealed hierarchy and a switch expression. The second adds the source-generated pieces.
// A closed set of outcomes. Adding a new case makes every switch below warn until it is handled.
public abstract record TransitionResult
{
public sealed record Allowed(TaskState To) : TransitionResult;
public sealed record Denied(string Reason) : TransitionResult;
public sealed record RequiresApproval(string Approver) : TransitionResult;
}
public static TransitionResult Decide(TaskState from, TaskState to, UserRole role) => (from, to, role) switch
{
(TaskState.Todo, TaskState.InProgress, _) => new TransitionResult.Allowed(to),
(TaskState.InProgress, TaskState.Done, _) => new TransitionResult.Allowed(to),
(TaskState.Done, TaskState.Todo, UserRole.Admin) => new TransitionResult.Allowed(to),
(TaskState.Done, TaskState.Todo, _) => new TransitionResult.RequiresApproval("project-owner"),
_ => new TransitionResult.Denied($"Cannot move from {from} to {to}."),
};
// Mapping outcomes to HTTP: the compiler checks the switch covers every case of the hierarchy.
static IResult ToHttp(TransitionResult r) => r switch
{
TransitionResult.Allowed a => Results.Ok(new { state = a.To }),
TransitionResult.RequiresApproval p => Results.Accepted(value: new { approver = p.Approver }),
TransitionResult.Denied d => Results.Problem(d.Reason, statusCode: StatusCodes.Status409Conflict),
_ => throw new UnreachableException(),
};
// List and property patterns: validate the shape of input before using it.
static bool IsBatchOfOneOrTwo(int[] ids) => ids is [_] or [_, _];// Source-generated JSON: no reflection, trimming and AOT friendly, and only the listed types are serializable.
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(TaskDto))]
[JsonSerializable(typeof(List<TaskDto>))]
[JsonSerializable(typeof(ProblemDetails))]
internal partial class AppJsonContext : JsonSerializerContext;
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));
// Source-generated logging: structured, allocation friendly, and the parameters are explicit.
public static partial class Log
{
[LoggerMessage(EventId = 1001, Level = LogLevel.Information, Message = "Task {TaskId} moved to {State} by {UserId}")]
public static partial void TaskMoved(ILogger logger, int taskId, TaskState state, string userId);
}
// Source-generated regex with a timeout, because this runs on user input.
public static partial class Validators
{
[GeneratedRegex(@"^[a-z0-9]+(?:-[a-z0-9]+)*$", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 100)]
public static partial Regex Slug();
}
// Use: if (!Validators.Slug().IsMatch(slug)) return Results.ValidationProblem(...);
// Polymorphism with an explicit allowlist of derived types, never arbitrary type names.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(EmailChannel), "email")]
[JsonDerivedType(typeof(WebhookChannel), "webhook")]
public abstract record NotificationChannel;Because the switch expression covers a sealed set, adding a fourth outcome such as Deferred makes the compiler flag the mapping function, so the HTTP layer cannot silently miss it.
Real-World Examples
- In July 2016 a regular expression that trimmed whitespace caused Stack Overflow to go down for about 34 minutes after a malformed post triggered catastrophic backtracking on the web servers. In July 2019 a regular expression in a new firewall rule caused CPU exhaustion across Cloudflare's network and a global outage of about 27 minutes. Both are the standard reasons to apply match timeouts and non-backtracking engines to expressions that handle untrusted input.
- Microsoft's guidance on BinaryFormatter states that it cannot be made safe for untrusted data, and the type was deprecated for several releases before its implementation was removed in .NET 9. Deserialization vulnerabilities in .NET, Java, and other platforms have repeatedly led to remote code execution, which is why explicit types and allowlists are the recommended approach.
Review Questions & Answers
The compiler knows all the possible cases and warns when a switch does not handle one, so adding a new case surfaces every place that must be updated. With if statements a forgotten case silently falls through to a default that may be wrong.
It generates the code at compile time and includes it in the build, so no reflection or runtime code generation is needed. That makes the code faster, works with trimming and Native AOT, and limits serialization to the types you listed.
Certain patterns take exponentially longer as crafted input grows, tying up a CPU and enabling denial of service. Generated regexes support a match timeout and the non-backtracking option, which bound or eliminate the problem when running on untrusted input.
If the payload chooses the type to create, an attacker can pick classes whose construction or callbacks run harmful code, which has produced many remote code execution vulnerabilities. Deserializing into fixed types, or a fixed allowlist of derived types, removes that choice.