📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Visitor pattern and double dispatch? Explain how ExpressionVisitor and Roslyn's syntax walkers use it, why switch expressions with pattern matching are often the modern alternative in C#, what the expression problem is, and when you would still choose a classic visitor.

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.

Senior Theory Advanced design-patterns double-dispatch expression-trees pattern-matching roslyn visitor

🎯 Key points

  • Visitor separates operations from a stable object structure: each node has Accept(visitor), which calls visitor.Visit(this) with the node's static type
  • Double dispatch: the call depends on both the node's runtime type (virtual Accept) and the visitor's runtime type (virtual Visit overload)
  • Expression problem: OO makes adding node types easy and operations hard; Visitor flips it, making operations easy and new node types hard (every visitor changes)
  • ExpressionVisitor walks and rewrites expression trees (VisitBinary, VisitMember, VisitParameter); EF Core's query pipeline and LINQ providers are built on it
  • Roslyn: CSharpSyntaxWalker traverses syntax trees for analysers; CSharpSyntaxVisitor<T> returns results; CSharpSyntaxRewriter produces modified trees
  • Pattern matching (switch expression over sealed records) gives single-function operations without Accept boilerplate, but C# 14 can't prove exhaustiveness over a class hierarchy, so a discard arm is needed
  • A classic visitor wins when the hierarchy is large and external code adds operations, and you want a compile error in every visitor when a node type is added
  • Danger: a discard arm that silently ignores unknown nodes can drop filters or rules; throw for unknown nodes and test

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 calls visitor.Visit(this). Because this has the node's static type inside each class, overload resolution picks Visit(AddNode) or Visit(NumberNode). That's double dispatch: the code that runs depends on the runtime type of the node, through the virtual Accept, and the runtime type of the visitor. A new operation is just a new visitor class.

The framework uses this heavily. ExpressionVisitor walks a LINQ expression tree with methods like VisitBinary, VisitMember and VisitParameter, 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 subclass CSharpSyntaxWalker and override VisitInvocationExpression to find every call to a banned API, and CSharpSyntaxRewriter produces 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 Accept boilerplate 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."


The expression problem

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

Where .NET uses Visitor

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

Visitor vs pattern matching

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

Production example

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.

🔍 What the interviewer is checking

Checks deep understanding of dispatch in C#, the expression problem, where .NET uses Visitor, and judgement between Visitor and pattern matching.

Green flags

  • Explains why overloads alone don't give double dispatch.
  • Names ExpressionVisitor and Roslyn walkers/rewriters with real uses.
  • Explains the expression problem and which side Visitor favours.
  • Knows C# can't check exhaustiveness over class hierarchies and makes the discard arm throw.

Red flags

  • Describes Visitor only as "a class that visits objects".
  • Thinks pattern matching makes Visitor obsolete in every case.
  • Uses discard arms that return defaults in translators or rules.

📚 Learn in depth

1. Structure and double dispatch

«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.

2. Why not 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.

3. ExpressionVisitor

ExpressionVisitor.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:

  • Parameter replacement when combining two Expression<Func<T,bool>> predicates with AndAlso, so both bodies refer to the same parameter.
  • Inspection: collecting the properties a predicate touches, to allow-list sortable or filterable fields.
  • Rewriting: injecting a tenant filter or replacing a method call with a translatable equivalent.

EF Core's query compilation runs your expression through a chain of these visitors (normalisation, navigation expansion, translation to a relational representation, SQL generation).

4. Roslyn visitors

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.

5. Pattern matching as an alternative

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.

6. Costs and variations

  • Two virtual calls per node instead of one; negligible next to the work done.
  • Every new node type changes the visitor interface and all implementations (that's the intended compile-time safety, and the main maintenance cost).
  • A visitor with a base class that provides default "visit children" behaviour (like ExpressionVisitor) lets subclasses override only what they care about, at the cost of losing the compile error for new types.
  • Acyclic visitor variants use one small interface per node type and type tests, reducing coupling in very large hierarchies.

Try it yourself

  1. Build the Num/Add/Mul hierarchy with Accept and write Evaluator and Printer visitors.
  2. Add a Neg node and watch every visitor fail to compile. Then do the same with a switch expression and see what happens.
  3. Write an ExpressionVisitor that lists every member a predicate accesses; use it to reject sorting on non-allow-listed fields.
  4. Combine two predicates with Expression.AndAlso without a parameter-replacing visitor, pass it to EF Core and read the error; then fix it.
  5. Write a small CSharpSyntaxWalker that counts async void methods in a file.

💻 Code

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.");
    }
}

⚠ Common mistakes

  • Mistake: A switch-expression "visitor" whose discard arm returns a default value. Why it is wrong: New node types are silently ignored, which in filters or authorisation rules can expose data. Instead: Throw UnreachableException in the discard arm and test every node type, or use a visitor interface for compile errors.
  • Mistake: Applying Visitor to a hierarchy whose node types change often. Why it is wrong: Every new type edits every visitor, the opposite of what you need. Instead: Use virtual methods when types change more often than operations.
  • Mistake: Calling 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).
  • Mistake: Combining two 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.
  • Mistake: Overriding an 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.
  • Mistake: Using 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.
  • Mistake: Writing a visitor for a three-type hierarchy with one operation. Why it is wrong: Interface and Accept boilerplate for one function. Instead: A switch expression.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes switch expressions over records instead of a visitor Why: Checks pattern-matching features and when they beat polymorphism
    How to answer

    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.

  2. When: Candidate mentions ExpressionVisitor or EF Core translation Why: Checks building and inspecting expression trees that ExpressionVisitor walks
    How to answer

    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.

  3. When: Candidate mentions Roslyn syntax walkers Why: Checks Roslyn syntax trees and writing analysers with syntax walkers
    How to answer

    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.

🛠 Real-world problems: how you handle them

New filter node silently ignored, returning unfiltered tenant data
Situation
Multi-tenant reporting API at [company] translating a JSON filter DSL into EF Core predicates, [~300] tenants. The translator was a switch expression over filter node records with a discard arm returning `x => true`.
Signals
A tenant reported a report showing rows outside the selected date range; Application Insights showed the affected queries had no date predicate in the generated SQL; no errors logged.
Investigation
Captured the SQL with EF Core logging (`LogTo` at Information) for the failing request and compared it to the DSL payload. The new `Between` node from the latest frontend release had no arm in the translator, so it hit the discard arm. Searched for other discard arms returning defaults across translators.
Resolution
Immediate: hotfix adding the `Between` arm and changing the discard arm to throw, returning 400 for unknown nodes. Real fix: introduced `IFilterVisitor<T>` with `Accept` on every node so the SQL translator, the validator and the description printer all fail to compile when a node is added.
Prevention
Contract tests that enumerate every node type via reflection and assert each visitor handles it; integration tests running translated filters against SQL Server in Testcontainers; a review checklist item banning default-returning discard arms in translators; privacy incident review under [the APP 11 obligations] confirmed no cross-tenant exposure.

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.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me