Visitor intent, Accept/Visit double dispatch, the expression problem (adding types vs adding operations), ExpressionVisitor in LINQ providers and EF Core, Roslyn CSharpSyntaxWalker and CSharpSyntaxVisitor<T>, pattern-matching switch expressions over record hierarchies as the lighter alternative, exhaustiveness limits in C# 14, costs, and when a classic visitor still wins.
Visitor separates operations from a stable object structure. Each node implements Accept(visitor), which calls visitor.Visit(this). That's double dispatch: the method chosen depends on both the node's and the visitor's runtime types, so you can add new operations (evaluate, print, translate to SQL) without touching the node classes.
It answers one side of the expression problem: OO makes new types easy and new operations hard; Visitor makes new operations easy and new types hard.
.NET relies on it: ExpressionVisitor underpins LINQ providers and EF Core translation; Roslyn's CSharpSyntaxWalker and CSharpSyntaxRewriter drive analysers.
In application code, a switch expression over sealed records is usually lighter. The trade-off: C# 14 can't check exhaustiveness over a class hierarchy, so a classic visitor still wins when you want every operation to break at compile time when a node type is added.
"Visitor is for when you have a fairly fixed set of node types, like an expression tree or a document model, and you keep adding operations over them: evaluate it, print it, validate it, translate it to SQL. Instead of adding a method to every node class for each new operation, each node gets one method,
Accept(IVisitor visitor), which callsvisitor.Visit(this). Becausethishas the node's static type inside each class, overload resolution picksVisit(AddNode)orVisit(NumberNode). That's double dispatch: the code that runs depends on the runtime type of the node, through the virtualAccept, and the runtime type of the visitor. A new operation is just a new visitor class.The framework uses this heavily.
ExpressionVisitorwalks a LINQ expression tree with methods likeVisitBinary,VisitMemberandVisitParameter, and returns a possibly rewritten tree. EF Core's query pipeline is a series of these visitors that normalise and translate your LINQ into SQL. Roslyn does the same for C# code: an analyser can subclassCSharpSyntaxWalkerand overrideVisitInvocationExpressionto find every call to a banned API, andCSharpSyntaxRewriterproduces a modified tree for code fixes. For example, at [company] I [used an ExpressionVisitor to ... / wrote an analyser that ...], which [result in brackets]. This ties to the expression problem: OO makes adding types easy and operations hard; Visitor flips that, and adding a node type now means changing every visitor.In my own application code I usually don't write the
Acceptboilerplate any more. With records and a switch expression,Eval(Expr e) => e switch { Num n => n.Value, Add a => Eval(a.Left) + Eval(a.Right), ... }gives me an operation as one function. The catch is that C# 14 has no closed hierarchies, so the compiler can't tell me I forgot a case; I need a discard arm, and that's where bugs hide. The mistake I see is a discard arm that returns a default, so a new node type is silently ignored, which in a filter translator means a filter is silently dropped. I use pattern matching for small hierarchies I own, and a classic visitor when a missed node type must be a compile error, not a production surprise."
| Design | Add a new type | Add a new operation |
|---|---|---|
| Virtual methods on the hierarchy (classic OO) | Easy: one new class | Hard: edit every class |
| Visitor | Hard: edit every visitor | Easy: one new visitor |
| Switch expression over records | Hard and silent if a discard arm hides it | Easy: one new function |
| API | Visitor type | Typical use |
|---|---|---|
System.Linq.Expressions.ExpressionVisitor |
Rewriting visitor | Query providers, parameter replacement, predicate combining |
| EF Core query pipeline | Many ExpressionVisitor subclasses |
Normalising and translating LINQ to SQL |
Roslyn CSharpSyntaxWalker |
Walker (no result) | Analysers collecting nodes |
Roslyn CSharpSyntaxVisitor<TResult> |
Visitor returning results | Computing values over syntax |
Roslyn CSharpSyntaxRewriter |
Rewriting visitor | Code fixes, refactorings |
| Classic visitor | Switch expression | |
|---|---|---|
| Boilerplate | Accept on every node, interface with a Visit per type |
None |
| New node type | Compile error in every visitor | Falls into the discard arm unless you throw |
| Operation state | Fields on the visitor | Parameters or closures |
| Best for | Large, stable hierarchies, many operations, external authors | Small hierarchies you own |
A reporting API translated a JSON filter DSL into EF Core predicates with a switch expression whose discard arm returned true. When a Between node was added to the DSL, the translator silently ignored it, and for about [two days] one tenant's report returned unfiltered rows. Replacing the discard arm with a throw, and later moving to an IFilterVisitor<T> interface, turned the next two node additions into compile errors instead of incidents.
Checks deep understanding of dispatch in C#, the expression problem, where .NET uses Visitor, and judgement between Visitor and pattern matching.
Green flags
ExpressionVisitor and Roslyn walkers/rewriters with real uses.Red flags
«interface» IExprVisitor<T>
Visit(Num) : T
Visit(Add) : T
Visit(Mul) : T
▲ ▲
Evaluator Printer (operations)
«abstract» Expr
Accept<T>(IExprVisitor<T> v) : T
▲ ▲ ▲
Num Add Mul (stable node types)
Accept => v.Visit(this) // this : Num, so Visit(Num) is chosen at compile time
C# method calls are single dispatch: a virtual call selects by the receiver's runtime type only, and overloads are chosen by the arguments' static types. Visitor gets a second dispatch by bouncing the call: node.Accept(visitor) dispatches on the node's runtime type, and inside, visitor.Visit(this) dispatches on the visitor's runtime type with an overload chosen by this's static type, which is exact.
dynamic or overloads alone?visitor.Visit(node) with node typed as Expr picks Visit(Expr) at compile time, not Visit(Add). dynamic would dispatch at run time but costs a binder call, loses compile-time checking and doesn't work in Native AOT. Accept makes the dispatch static, fast and checked.
ExpressionVisitorExpressionVisitor.Visit(Expression) dispatches on NodeType to virtual methods (VisitBinary, VisitMember, VisitMethodCall, VisitLambda<T>, VisitParameter and more). Each default implementation visits children and rebuilds the node only if a child changed (node.Update(...)), so unchanged subtrees are reused. Common uses:
Expression<Func<T,bool>> predicates with AndAlso, so both bodies refer to the same parameter.EF Core's query compilation runs your expression through a chain of these visitors (normalisation, navigation expansion, translation to a relational representation, SQL generation).
Syntax trees are immutable. CSharpSyntaxWalker visits every node (and optionally tokens and trivia) for analysis; CSharpSyntaxVisitor<TResult> returns a value per node; CSharpSyntaxRewriter returns a new tree, which is how code fixes produce edits. Analysers usually register callbacks with RegisterSyntaxNodeAction rather than walking manually, but the walker is the same idea.
Records plus switch expressions give "functions over a closed set" without Accept:
static decimal Eval(Expr e) => e switch
{
Num n => n.Value,
Add a => Eval(a.Left) + Eval(a.Right),
_ => throw new UnreachableException($"Unknown node {e.GetType().Name}")
};
The compiler checks exhaustiveness for enums, bool and tuples of them, but for a class hierarchy it can't know there are no other subclasses (even with a sealed leaf, the base can be derived elsewhere in the assembly). Union types are being designed for a future C# version, which would close this gap; until then the discard arm must throw, and tests must cover every node type.
ExpressionVisitor) lets subclasses override only what they care about, at the cost of losing the compile error for new types.Num/Add/Mul hierarchy with Accept and write Evaluator and Printer visitors.Neg node and watch every visitor fail to compile. Then do the same with a switch expression and see what happens.ExpressionVisitor that lists every member a predicate accesses; use it to reject sorting on non-allow-listed fields.Expression.AndAlso without a parameter-replacing visitor, pass it to EF Core and read the error; then fix it.CSharpSyntaxWalker that counts async void methods in a file.A classic visitor over a small rule AST, the pattern-matching alternative, and an ExpressionVisitor used for inspection.
namespace Rules;
// Stable node types
public abstract record Expr
{
public abstract T Accept<T>(IExprVisitor<T> visitor);
}
public sealed record Num(decimal Value) : Expr
{
public override T Accept<T>(IExprVisitor<T> v) => v.Visit(this); // 'this' is Num: Visit(Num) chosen statically
}
public sealed record Add(Expr Left, Expr Right) : Expr
{
public override T Accept<T>(IExprVisitor<T> v) => v.Visit(this);
}
public sealed record Mul(Expr Left, Expr Right) : Expr
{
public override T Accept<T>(IExprVisitor<T> v) => v.Visit(this);
}
// Adding a node type adds a method here, breaking every visitor at compile time (on purpose)
public interface IExprVisitor<out T>
{
T Visit(Num node);
T Visit(Add node);
T Visit(Mul node);
}
// Operations are separate classes; the nodes never change
public sealed class Evaluator : IExprVisitor<decimal>
{
public decimal Visit(Num n) => n.Value;
public decimal Visit(Add a) => a.Left.Accept(this) + a.Right.Accept(this);
public decimal Visit(Mul m) => m.Left.Accept(this) * m.Right.Accept(this);
}
public sealed class Printer : IExprVisitor<string>
{
public string Visit(Num n) => n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
public string Visit(Add a) => $"({a.Left.Accept(this)} + {a.Right.Accept(this)})";
public string Visit(Mul m) => $"{m.Left.Accept(this)} * {m.Right.Accept(this)}";
}
// Pattern-matching alternative: one function, no Accept. The discard arm MUST throw.
public static class ExprFunctions
{
public static decimal Eval(Expr e) => e switch
{
Num n => n.Value,
Add a => Eval(a.Left) + Eval(a.Right),
Mul m => Eval(m.Left) * Eval(m.Right),
_ => throw new System.Diagnostics.UnreachableException($"Unhandled node {e.GetType().Name}")
};
}
// var expr = new Add(new Num(2), new Mul(new Num(3), new Num(4)));
// expr.Accept(new Evaluator()); // 14
// expr.Accept(new Printer()); // (2 + 3 * 4)
// ExprFunctions.Eval(expr); // 14
namespace Queries;
using System.Linq.Expressions;
// ExpressionVisitor for inspection: which properties does a client-supplied sort or filter touch?
public sealed class MemberCollector : ExpressionVisitor
{
public HashSet<string> Members { get; } = new(StringComparer.Ordinal);
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression is ParameterExpression) // only direct properties of the entity
Members.Add(node.Member.Name);
return base.VisitMember(node); // keep walking children
}
}
public static class QueryGuards
{
private static readonly HashSet<string> Allowed = ["Name", "Price", "CreatedAt"];
public static void EnsureAllowed<T>(Expression<Func<T, object>> sortKey)
{
var collector = new MemberCollector();
collector.Visit(sortKey);
var forbidden = collector.Members.Except(Allowed).ToList();
if (forbidden.Count > 0)
throw new ArgumentException($"Sorting on {string.Join(", ", forbidden)} is not allowed.");
}
}
UnreachableException in the discard arm and test every node type, or use a visitor interface for compile errors.visitor.Visit(node) with node typed as the base class and expecting the specific overload. Why it is wrong: Overloads bind on static type, so Visit(Expr) is chosen. Instead: Dispatch through node.Accept(visitor).Expression<Func<T,bool>> predicates with Expression.AndAlso without replacing parameters. Why it is wrong: The bodies refer to different ParameterExpressions and EF Core fails to translate. Instead: Use an ExpressionVisitor that replaces one parameter with the other.ExpressionVisitor method and not calling base. Why it is wrong: Child nodes are never visited, so nested members or calls are missed. Instead: Return base.VisitX(node) unless you intentionally stop.dynamic to get double dispatch. Why it is wrong: Runtime binder cost, no compile-time checks, and not AOT-friendly. Instead: Accept/Visit or pattern matching.Accept boilerplate for one function. Instead: A switch expression.I rarely write classic visitors in application code now, but I read them constantly: EF Core, Roslyn and LINQ providers are built on them, and understanding ExpressionVisitor is what lets you debug "could not be translated" errors or write predicate-combining helpers. The design decision is which axis changes more: node types or operations, and whether a forgotten case must fail at compile time.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Virtual methods on nodes | Types change often, few operations | Each operation spreads across classes | Many operations added by others |
| Classic visitor | Stable, large hierarchy; many operations; compile-time safety on new types | Accept boilerplate; every visitor changes per new type |
Small hierarchies you own |
| Switch expression over records | Small hierarchy, operations as functions | Silent gaps unless the discard throws | Safety-critical translations with frequent new nodes |
ExpressionVisitor subclass |
Inspecting or rewriting LINQ expressions | Must understand node types and base calls |
When a simple lambda will do |
Measure correctness, not speed: a test per node type per operation, and for translators, an integration test that runs the generated query against a real database.
C# patterns now cover most data checks. There are type, constant and null patterns, relational ones like >= 100, logical and, or and not combinators, and property patterns, including extended ones like { Customer.Address.State: "NSW" }. There are also positional patterns that use Deconstruct, var and discard patterns, and list patterns like [first, .., last]. The compiler turns a switch into an efficient decision tree, warns when it isn't exhaustive, and errors on unreachable cases. I use patterns for closed sets of data shapes and polymorphism when new types keep being added.
An expression tree is code represented as data. If you assign a lambda to Expression<Func<Order,bool>>, the compiler builds an object tree of parameter, member, binary and constant nodes instead of IL, and that is what lets EF Core read your Where and turn it into SQL. You can build trees with the Expression factory methods, rewrite them with ExpressionVisitor, and turn them into delegates with Compile(). Compiling is expensive, so cache the result, and under Native AOT it falls back to a slower interpreter. Only expression-bodied lambdas qualify, and features like ?., tuple literals and switch expressions are not allowed.
Roslyn is the C# compiler exposed as an API: code becomes syntax trees, a semantic model that knows what every symbol means, and language-neutral operations. A Roslyn analyser is a plug-in that subscribes to those and reports diagnostics in the IDE and in every build, so team rules become compiler warnings or errors instead of review comments. Start with what ships with the SDK: the .NET analysers (CAxxxx) and code style rules (IDExxxx), tuned with AnalysisLevel/AnalysisMode, .editorconfig severities and EnforceCodeStyleInBuild. BannedApiAnalyzers bans specific APIs from a BannedSymbols.txt file with no custom code. When you need a domain rule, write a DiagnosticAnalyzer targeting netstandard2.0, register operation or symbol actions, enable concurrent execution, test it, and ship it as a NuGet package or project reference.
How to tell it (STAR)
**S:** At [company], a tenant noticed their report ignored the date range they had selected. **T:** I owned the filter translator and needed to find out why and make sure a missed case could never fail silently again. **A:** EF Core's SQL logging showed the date predicate was missing; the frontend had added a `Between` node and our switch expression's discard arm turned unknown nodes into `true`. I hotfixed it and made unknown nodes throw, then moved the translator, validator and printer to a visitor interface so a new node is a compile error, with a reflection-based test that every visitor handles every node. **R:** The fix shipped within [hours], and the next [two] node additions surfaced as compile errors in CI instead of production incidents.
Last updated 18 Nov 2026.