BehavioralC#verifiedVerified

Visitor Pattern in C#

Lets you add new operations to an object structure without modifying the objects themselves, by separating the algorithm from the object structure it operates on.

How to Implement the Visitor Pattern in C#

1Step 1: Define the visitor interface

public interface IShapeVisitor<out TResult>
{
    TResult Visit(Circle circle);
    TResult Visit(Rectangle rectangle);
}

2Step 2: Elements accept visitors

public interface IShape
{
    TResult Accept<TResult>(IShapeVisitor<TResult> visitor);
}

public class Circle(double radius) : IShape
{
    public double Radius => radius;
    public TResult Accept<TResult>(IShapeVisitor<TResult> visitor) =>
        visitor.Visit(this);
}

public class Rectangle(double width, double height) : IShape
{
    public double Width => width;
    public double Height => height;
    public TResult Accept<TResult>(IShapeVisitor<TResult> visitor) =>
        visitor.Visit(this);
}

3Step 3: Concrete visitor computes area

public class AreaCalculator : IShapeVisitor<double>
{
    public double Visit(Circle c) =>
        Math.PI * c.Radius * c.Radius;

    public double Visit(Rectangle r) =>
        r.Width * r.Height;
}

// Usage:
// IShape shape = new Circle(5);
// var area = shape.Accept(new AreaCalculator()); // ~78.54

Visitor Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Visitor Pattern in the Real World

Think of a tax auditor visiting different types of businesses—a restaurant, a law firm, a retail shop. The auditor (visitor) knows exactly what to examine at each type of business and applies the appropriate inspection procedure. The businesses (elements) simply let the auditor in; they don't change their own operations to accommodate the audit.