Large switch statements are not always a problem. They become a problem when the same set of cases is repeated across services, controllers, validators, formatters, and business logic.
A common example is an application that processes different payment methods:
switch (payment.Method)
{
case PaymentMethod.Card:
// Card logic
break;
case PaymentMethod.BankTransfer:
// Bank transfer logic
break;
case PaymentMethod.Wallet:
// Wallet logic
break;
case PaymentMethod.Cash:
// Cash logic
break;
}This looks manageable at first. The problem appears when each case grows or when the same switch needs to be updated in several places.
C# 15 introduces language features around closed hierarchies and union-style modeling that make this kind of code easier to structure. The goal is not to eliminate every switch, but to move behavior closer to the types that represent it and make the set of valid alternatives explicit.
What Is a Closed Hierarchy?
A closed hierarchy describes a type with a known set of permitted alternatives.
Conceptually:
Payment
|
+-- CardPayment
+-- BankTransferPayment
+-- WalletPayment
+-- CashPaymentThe important property is that the application knows the complete set of supported payment types.
This is different from an open inheritance hierarchy where any assembly can introduce another implementation:
public abstract class Payment
{
}With an open design, another developer can potentially create:
public sealed class CryptocurrencyPayment : Payment
{
}A closed hierarchy is useful when the business domain has a deliberately limited set of alternatives.
The Problem With Large Switch Statements
Consider an order processor:
public decimal CalculateFee(Payment payment)
{
switch (payment.Method)
{
case PaymentMethod.Card:
return payment.Amount * 0.02m;
case PaymentMethod.BankTransfer:
return 10m;
case PaymentMethod.Wallet:
return payment.Amount * 0.01m;
case PaymentMethod.Cash:
return 0m;
default:
throw new ArgumentOutOfRangeException();
}
}Now imagine another operation:
public string GetDisplayName(Payment payment)
{
switch (payment.Method)
{
case PaymentMethod.Card:
return "Card";
case PaymentMethod.BankTransfer:
return "Bank Transfer";
case PaymentMethod.Wallet:
return "Wallet";
case PaymentMethod.Cash:
return "Cash";
default:
throw new ArgumentOutOfRangeException();
}
}And another:
public bool RequiresAuthorization(Payment payment)
{
switch (payment.Method)
{
// More cases
}
}The same business knowledge is now duplicated.
Adding a new payment method means finding every switch and remembering to update it.
Replace the Enum With Domain Types
Instead of representing the payment method as an enum, create explicit domain types.
public abstract record Payment;
public sealed record CardPayment(
decimal Amount) : Payment;
public sealed record BankTransferPayment(
decimal Amount) : Payment;
public sealed record WalletPayment(
decimal Amount) : Payment;
public sealed record CashPayment(
decimal Amount) : Payment;Now the payment itself contains information about what it represents.
The application no longer needs a separate Method property to identify the type.
Move Behavior Into the Hierarchy
The next step is deciding whether the behavior belongs with the type.
For example:
public abstract record Payment
{
public abstract decimal CalculateFee();
}
public sealed record CardPayment(
decimal Amount) : Payment
{
public override decimal CalculateFee()
=> Amount * 0.02m;
}
public sealed record BankTransferPayment(
decimal Amount) : Payment
{
public override decimal CalculateFee()
=> 10m;
}
public sealed record WalletPayment(
decimal Amount) : Payment
{
public override decimal CalculateFee()
=> Amount * 0.01m;
}
public sealed record CashPayment(
decimal Amount) : Payment
{
public override decimal CalculateFee()
=> 0m;
}The caller becomes much simpler:
var fee = payment.CalculateFee();There is no switch in the calling code.
The behavior is associated with the type that owns the relevant business rule.
When a Switch Is Still Better
This does not mean every switch should be replaced with polymorphism.
Suppose the application needs to generate a report:
Payment
|
+-- Card
+-- Bank Transfer
+-- Wallet
+-- CashThe reporting requirement may belong to the reporting layer rather than the payment domain object.
In that situation, pattern matching can be appropriate:
return payment switch
{
CardPayment card =>
$"Card: {card.Amount:C}",
BankTransferPayment transfer =>
$"Bank transfer: {transfer.Amount:C}",
WalletPayment wallet =>
$"Wallet: {wallet.Amount:C}",
CashPayment cash =>
$"Cash: {cash.Amount:C}",
_ => throw new ArgumentOutOfRangeException()
};The problem is not the switch itself.
The problem is a switch that becomes the central location for every behavior in the system.
Closed Hierarchies Improve Domain Modeling
Consider an order state.
A typical implementation might use:
public enum OrderStatus
{
Pending,
Confirmed,
Shipped,
Delivered,
Cancelled
}This is simple, but the enum does not carry state-specific information.
A closed hierarchy can model richer states:
OrderState
|
+-- Pending
+-- Confirmed
+-- Shipped
+-- Delivered
+-- CancelledFor example:
public abstract record OrderState;
public sealed record Pending : OrderState;
public sealed record Confirmed(DateTime ConfirmedAt)
: OrderState;
public sealed record Shipped(
string TrackingNumber) : OrderState;
public sealed record Delivered(
DateTime DeliveredAt) : OrderState;
public sealed record Cancelled(
string Reason) : OrderState;Now each state can contain only the information relevant to it.
A shipped order has a tracking number.
A cancelled order has a cancellation reason.
A pending order does not need either.
Closed Types and Exhaustive Handling
One of the biggest advantages of a closed hierarchy is that the compiler and the type system can help developers reason about all valid cases.
For example:
static string Describe(OrderState state)
{
return state switch
{
Pending => "Order is waiting for confirmation",
Confirmed confirmed =>
$"Confirmed at {confirmed.ConfirmedAt}",
Shipped shipped =>
$"Tracking: {shipped.TrackingNumber}",
Delivered delivered =>
$"Delivered at {delivered.DeliveredAt}",
Cancelled cancelled =>
$"Cancelled: {cancelled.Reason}"
};
}If a new state is added, consumers that assume the existing set of cases may need to be reviewed.
This is one of the main benefits of modeling a finite domain explicitly.
Avoid the Default Case When Possible
A common pattern is:
return state switch
{
Pending => "...",
Confirmed => "...",
Shipped => "...",
Delivered => "...",
Cancelled => "...",
_ => throw new InvalidOperationException()
};The default case can hide missing cases.
If the hierarchy is intentionally closed and the compiler can prove that the alternatives are handled, an exhaustive switch without a catch-all can provide stronger feedback when the model changes.
This is particularly useful in domain code where silently ignoring a new state could create a business bug.
Closed Hierarchies for Command Handling
Another useful example is application commands.
Suppose an order system accepts several commands:
CreateOrder
CancelOrder
ShipOrder
RefundOrderA generic command interface might look like:
public abstract record OrderCommand;
public sealed record CreateOrder(
int CustomerId) : OrderCommand;
public sealed record CancelOrder(
int OrderId,
string Reason) : OrderCommand;
public sealed record ShipOrder(
int OrderId,
string TrackingNumber) : OrderCommand;
public sealed record RefundOrder(
int OrderId,
decimal Amount) : OrderCommand;A handler can then use pattern matching:
public async Task HandleAsync(OrderCommand command)
{
switch (command)
{
case CreateOrder create:
await CreateAsync(create);
break;
case CancelOrder cancel:
await CancelAsync(cancel);
break;
case ShipOrder ship:
await ShipAsync(ship);
break;
case RefundOrder refund:
await RefundAsync(refund);
break;
}
}The command hierarchy provides a clear boundary.
Every command is an explicit type instead of a generic object containing a collection of optional properties.
Closed Hierarchies Versus Strategy Pattern
The Strategy pattern is useful when behavior needs to be selected dynamically.
For example:
public interface IPaymentProcessor
{
Task ProcessAsync(Payment payment);
}Different implementations can be registered through dependency injection.
That is appropriate when the set of implementations is intentionally extensible.
A closed hierarchy is a better fit when the alternatives are part of a known domain model.
Approach | Best Fit |
|---|---|
Large switch | Small, localized set of cases |
Enum + switch | Simple state with little associated data |
Closed hierarchy | Finite domain alternatives |
Strategy pattern | Pluggable or replaceable behavior |
Interface hierarchy | Extensible implementation model |
Factory | Object creation based on a known condition |
The important question is whether the set of alternatives is open or closed.
C# 15 and Closed Type Modeling
Modern C# provides stronger tools for expressing closed sets of types and working with pattern matching.
The direction is important for application architecture: instead of representing every variation with flags, enums, nullable properties, and large switches, the type system can express more of the domain directly.
A design such as:
Payment
|
+-- CardPayment
+-- WalletPayment
+-- BankTransferPaymentis easier to understand than:
Payment payment
bool IsCard
bool IsWallet
bool IsBankTransfer
string? CardNumber
string? WalletId
string? BankAccountThe second design allows invalid combinations.
A closed hierarchy can make those invalid states harder to represent.
Avoid Boolean Combinations
One common source of large switches is a class with multiple Boolean flags.
For example:
public sealed class Notification
{
public bool IsEmail { get; set; }
public bool IsSms { get; set; }
public bool IsPush { get; set; }
}This allows invalid combinations:
Email = true
SMS = true
Push = trueIf the application expects exactly one notification channel, explicit types are clearer:
public abstract record Notification;
public sealed record EmailNotification(
string Address) : Notification;
public sealed record SmsNotification(
string PhoneNumber) : Notification;
public sealed record PushNotification(
string DeviceToken) : Notification;Now the type itself communicates the rule.
Keep Hierarchies Small
A closed hierarchy should represent a meaningful concept.
Avoid creating dozens of types simply to eliminate every switch.
For example, if a calculation really is a simple mapping:
var multiplier = payment.Method switch
{
PaymentMethod.Card => 0.02m,
PaymentMethod.Wallet => 0.01m,
PaymentMethod.Cash => 0m,
_ => throw new ArgumentOutOfRangeException()
};there may be no reason to introduce a hierarchy.
Use a hierarchy when the alternatives have different data, behavior, lifecycle rules, or domain meaning.
Common Mistakes
Replacing every switch
Not every switch is a design problem.
Small, local switches are often the clearest solution.
Creating an open hierarchy for a closed domain
If the business rules define a finite set of alternatives, make that intention clear in the design.
Moving all behavior into domain classes
Some behavior belongs in application or presentation layers.
Do not create an anemic service layer simply to avoid a switch.
Using a generic base type everywhere
A hierarchy should represent a real domain relationship.
Avoid:
BaseThing
ThingA
ThingB
ThingCwithout meaningful domain semantics.
Keeping duplicate switch logic
If the same set of cases appears across multiple methods, that is a strong signal to review the model.
Best Practices
Use closed hierarchies for genuinely finite domain concepts.
Give each alternative a meaningful name.
Store state-specific data on the relevant type.
Use pattern matching for behavior that belongs outside the hierarchy.
Prefer exhaustive handling where the domain is intentionally closed.
Avoid unnecessary default cases when they hide missing alternatives.
Keep REST, persistence, and domain models separate when their responsibilities differ.
Add tests for every important alternative.
Review all consumers when a new hierarchy member is introduced.
Advantages
Advantage | Description |
|---|---|
Clear domain model | Business alternatives become explicit types |
Less duplicated logic | Shared switches can be reduced |
Better state representation | Each type can hold relevant data |
Safer changes | New cases become easier to identify |
Better pattern matching | Type-specific behavior is easier to express |
Fewer invalid states | Type design can prevent invalid combinations |
Disadvantages and Considerations
Consideration | Impact |
|---|---|
More classes | Small domains can become unnecessarily verbose |
Migration effort | Existing enum-based code needs refactoring |
Serialization | External contracts need deliberate mapping |
Persistence | Database state may still use enums or codes |
Overengineering | Simple switches may become harder to understand |
API evolution | New alternatives can affect many consumers |
A Practical Migration Approach
Do not rewrite a large application in one step.
Start by identifying a switch that has become difficult to maintain.
Then:
Identify the finite set of business alternatives.
Determine whether the behavior belongs to the domain type or the consuming layer.
Create the closed hierarchy.
Move state-specific data into the appropriate types.
Replace the original switch gradually.
Add tests for every alternative.
Search the codebase for other switches using the old representation.
Remove the old enum or flag-based model only after all consumers have migrated.
This keeps the refactoring incremental.
Summary
Large switch statements are often a symptom rather than the actual problem. The deeper issue is usually that the application represents several distinct business concepts as one generic value.
Closed hierarchies provide a way to model those alternatives explicitly:
Payment
|
+-- CardPayment
+-- WalletPayment
+-- BankTransferPayment
+-- CashPaymentThe result is a domain model that communicates its valid states directly.
C# pattern matching remains useful, especially when behavior belongs to an external concern such as reporting, serialization, or API mapping. The goal is not to remove switch statements completely.
The better goal is to use the type system to place business rules where they belong and reserve large switches for situations where they genuinely make the code clearer.
When a switch repeatedly appears across the application for the same finite set of cases, that is a good point to stop and ask whether the type model is doing enough of the work.

Join the conversation! Your thoughts help the community grow.