Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
C#

C#

A productive, strongly typed language for the whole .NET platform.

Paradigm
OOP, functional features
Typing
Static, strong, nullable-aware
Memory
Generational GC
Runs
.NET runtime (JIT) or Native AOT
Concurrency
Tasks, async/await, channels
Behavioral pattern

Visitor

Intent

Separates algorithms from the objects on which they operate.

Problem

You need to export a graph of nodes to XML, then JSON, then calculate metrics, without editing node classes each time.

Solution

Put each operation in a visitor class with one method per element type; elements accept a visitor (double dispatch).

Real-world analogy

Think of it like this

An insurance agent visiting a street: a home gets home insurance, a bank gets theft insurance, a shop gets fire insurance.

Structure

association / extends implements / depends on
«interface» Visitor + visit(e: ElementA)+ visit(e: ElementB) 1 ConcreteVisitors + visit(e: ElementA)+ visit(e: ElementB) 2 «interface» Element + accept(v: Visitor) 3 ElementA + accept(v) 4 ElementB + accept(v)

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Visitor — Visitor declares one visit method per concrete element type.
  2. 2ConcreteVisitors — Concrete Visitors implement one operation for every element type.
  3. 3Element — Element declares accept(), which takes a visitor.
  4. 4ElementA — Concrete Elements call the visit method that matches their own class (double dispatch).

Code example

A C# code sample for Visitor is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Visitor when performing an operation on all elements of a complex structure.

Use Visitor when keeping auxiliary behaviour out of domain classes.

Pros and cons

Pros

  • Open–Closed for operations
  • Accumulates state while traversing

Cons

  • Every visitor changes when an element type is added

Relations with other patterns

Check yourself

Check yourself

Add an export-to-JSON operation across a hierarchy of syntax-tree node classes without modifying them.

Saved in this browser only. Part of Behavioral patterns (0/11).