Skip to content

Version 10.x.x Discriminated Unions

Pawel Gerr edited this page Nov 18, 2026 · 1 revision

Discriminated unions are a powerful feature that allows a type to hold a value that could be one of several different types. They bring type safety and exhaustive pattern matching to these scenarios — the compiler ensures every case is handled, eliminating an entire class of runtime errors.

This guide covers the basics. For advanced topics, see the companion pages:

Articles

Why Discriminated Unions?

Traditional C# approaches for representing values with multiple possible outcomes often lead to runtime errors and code that's difficult to maintain. Here are three common patterns and their pitfalls:

Tuples with nullable fields — A method that loads an order from the database returns (Order? Order, bool IsSoftDeleted, string? Error) to represent three possible outcomes: the order was found, it was soft-deleted, or an error occurred. The type system doesn't prevent invalid combinations (e.g., order is null, error is null, and isSoftDeleted is false). Correct interpretation relies on conventions, not the compiler.

Result<T> with boolean flags — A generic Result<T> class with IsSuccess, Value, and Error properties. The compiler doesn't prevent accessing Value when IsSuccess is false, leading to potential NullReferenceException. There's no exhaustiveness guarantee — adding new states to the status flag doesn't produce compile errors at call sites.

Exceptions for control flow — Using exceptions for expected outcomes like "not found" creates performance overhead, obscures normal flow, and requires the caller to know which exceptions a method might throw (unlike return types, exceptions aren't part of the method signature).

Discriminated unions solve these problems by modeling the alternatives directly in the type system. A Result<T> refactored as a union can only be Success or Failure — never both, never neither. The library generates a Switch method that requires a handler for every case — forget one, and the code won't compile:

[RegularUnion]
public partial record Result<T>
{
    public sealed record Success(T Value) : Result<T>;
    public sealed record Failure(string Error) : Result<T>;
}

Result<Order> result = GetOrder(123);

result.Switch(
    success: s => Handle(s.Value),
    failure: f => Handle(f.Error)  // Compile error if you forget this
);

Identifying Discriminated Union Candidates in Your Code:

  • Classes with "type flags" or enums used to determine how to interpret other properties
  • Extensive switch/if-else chains based on an object's runtime type or status flag
  • Methods returning complex tuples with multiple nullable properties representing mutually exclusive outcomes
  • Base classes where derived classes mainly differ by the data they hold for a specific state

Getting Started

Installation

  • C# 11 (or higher) for generated code
  • SDK 8.0.416 (or higher) for building projects
  • NuGet package: Thinktecture.Runtime.Extensions

Choosing between Ad hoc and Regular Unions

The library provides two flavors of unions:

  • Ad hoc unions: Combine types that share no common base class into a single union type. Use these when the member types (generics) are unrelated and already exist independently (e.g., string, int, List<ValidationError>).
  • Regular unions: Model a type hierarchy where all cases derive from a common abstract base. Use these when the cases are conceptually related and benefit from shared behavior or properties.

C# 15 adds its own union declaration. See C# 15 unions and Thinktecture unions for the differences and for the combination of both.

Requirements (Ad hoc Unions)

  • The type must be declared as partial
  • Apply [AdHocUnion<T1, T2>] (member types as type arguments) or [AdHocUnion(typeof(T1), typeof(T2))] (member types as constructor arguments, when the generic approach is not possible)
  • The union type can be generic — use TypeParamRef1–TypeParamRef5 to reference the union's own type parameters (see Generic ad hoc unions)

Requirements (Regular Unions)

  • Base class must be partial
  • Apply [RegularUnion] attribute to the base type
  • Derived types must be nested inside the base type and be sealed or have a private constructor

Ad hoc unions

Ad hoc unions combine types that share no common base class into a single union type — the simplest way to get started.

What you implement

Create a partial class, struct or ref struct and annotate it with [AdHocUnion<T1, T2>] (member types as type arguments) or with [AdHocUnion(typeof(T1), typeof(T2))] (member types as constructor arguments).

The generic [AdHocUnion<T1, T2>] exists since version 10.7.0. With an older version of the library, write [Union<T1, T2>]. There [AdHocUnion<T1, T2>] fails with error CS0308 ("The non-generic type 'AdHocUnionAttribute' cannot be used with type arguments"). See [RegularUnion], [AdHocUnion] and [Union].

Generic approach (recommended for most cases)

// class
[AdHocUnion<string, int>]
public partial class TextOrNumber;

// struct
[AdHocUnion<string, int>]
public partial struct TextOrNumber;

// ref struct
[AdHocUnion<string, int>]
public ref partial struct TextOrNumber;

The generic AdHocUnionAttribute allows up to 5 member types:

[AdHocUnion<string, int, bool, Guid, char>]
public partial class MyUnion;

Non-generic approach (for complex type scenarios)

The non-generic AdHocUnionAttribute is useful when you need to specify types that cannot be expressed as generic type parameters, such as nullable reference types (List<string?>), or other edge cases where C# generic attribute constraints become limiting.

// Using AdHocUnion with typeof()
[AdHocUnion(typeof(string), typeof(int))]
public partial class TextOrNumber;

// Up to 5 types supported
[AdHocUnion(typeof(string), typeof(int), typeof(bool), typeof(Guid), typeof(char))]
public partial class MyUnion;

// Complex scenarios: nullable reference types in generic collections
[AdHocUnion(typeof(List<string?>), typeof(int))]
public partial class ListOrNumber;

Both approaches generate identical functionality. Use the generic approach for simplicity, and the non-generic approach when you hit generic attribute limitations.

What is implemented for you

The source generator creates a comprehensive set of features:

// Implicit conversion from one of the member types
TextOrNumber textOrNumberFromString = "text";
TextOrNumber textOrNumberFromInt = 42;

// Type checking
bool isText = textOrNumberFromString.IsString;
bool isNumber = textOrNumberFromString.IsInt32;

// Type-safe value access
// Throws "InvalidOperationException" if type doesn't match
string text = textOrNumberFromString.AsString;
int number = textOrNumberFromInt.AsInt32;

// Alternative: explicit casting
string text = (string)textOrNumberFromString;
int number = (int)textOrNumberFromInt;

// Get untyped value
object value = textOrNumberFromString.Value;

// Built-in equality comparison
bool equals = textOrNumberFromInt.Equals(textOrNumberFromString);
bool equal = textOrNumberFromInt == textOrNumberFromString;
bool notEqual = textOrNumberFromInt != textOrNumberFromString;

// ToString - delegates to the contained value's ToString()
string str = textOrNumberFromInt.ToString();  // "42"

// GetHashCode - delegates to the contained value's GetHashCode()
int hash = textOrNumberFromInt.GetHashCode();

Note: C# does not allow user-defined conversion operators from object or interface types. If a member type is object or an interface, no implicit or explicit conversion operator is generated for that type — use the constructor instead.

Accessibility: Every member type must be at least as accessible as the union itself. A public union with an internal member type does not compile, because the generated conversion operators, AsX properties, Switch/Map overloads, constructors and factory methods all expose that member type, and C# requires conversion operators to be public. The analyzer reports TTRESG077 for this case. Either make the union internal as well, or make the member type public.

Serialization and model binding: Ad hoc unions don't carry a type discriminator, so they can't be serialized as polymorphic JSON out of the box. To enable JSON serialization, ASP.NET Core model binding, or EF Core persistence, add [ObjectFactory<T>] to define how the union converts to/from a primitive type. See Framework Integration for a worked example.

Generic ad hoc unions

Ad hoc unions can be generic. Use the placeholder types TypeParamRef1 through TypeParamRef5 (from the Thinktecture namespace) to reference the union type's own type parameters. TypeParamRefN maps to the Nth type parameter (1-based).

Basic usage

Each TypeParamRef placeholder becomes the corresponding type parameter in the generated code:

using Thinktecture;

[AdHocUnion<TypeParamRef1, TypeParamRef2>]
public partial struct Either<T1, T2>;

// Usage — type parameter members don't get implicit conversion operators,
// use constructors or factory methods instead
Either<string, int> value = new Either<string, int>("hello");        // constructor
Either<string, int> number = Either<string, int>.CreateT2(42);       // factory method

Mixing type parameters with concrete types

You can combine TypeParamRef placeholders with concrete types in the same union:

using Thinktecture;

[AdHocUnion<TypeParamRef1, string>]
public partial struct Result<T>;

// Usage
Result<int> success = Result<int>.CreateT(42);  // factory method — T is a type parameter
Result<int> error = "Something failed";          // implicit conversion — string is a concrete type

The non-generic AdHocUnionAttribute works the same way:

using Thinktecture;

[AdHocUnion(typeof(TypeParamRef1), typeof(string))]
public partial struct Result<T>;

Nested generic usage

TypeParamRef placeholders can appear inside constructed generic types. The source generator resolves them to the actual type parameter:

using Thinktecture;

[AdHocUnion<TypeParamRef1, List<TypeParamRef1>>]
public partial struct SingleOrMany<T>;

// Usage
SingleOrMany<int> single = SingleOrMany<int>.CreateT(42);  // factory method — T is a type parameter
SingleOrMany<int> many = new List<int> { 1, 2, 3 };        // implicit conversion — List<int> is a concrete constructed type

What is generated for type parameter members

For union members that are type parameters, the source generator produces constructors and factory methods instead of conversion operators. C# allows the declaration of such operators, but their behavior depends on the actual type argument: for specific instantiations the conversion becomes ambiguous or is silently not applied. The generator therefore does not create them. If you control the instantiations of your union, you can declare the operator yourself; see Conversion operators for type parameter members.

When any member triggers factory method generation (type parameter, interface, System.Object, or duplicate type), factory methods are generated for all members — not just the triggering ones. Constructors and conversion operators are still generated for eligible members as usual.

[AdHocUnion<TypeParamRef1, string>]
public partial struct Result<T>;

// Type parameter member — use constructor or factory method (no implicit conversion available)
Result<int> success = new Result<int>(42);
Result<int> alsoSuccess = Result<int>.CreateT(42);

// Concrete type member — implicit conversion still works, factory method also available
Result<int> error = "Something failed";
Result<int> alsoError = Result<int>.CreateString("Something failed");

You can control factory method generation with the FactoryMethodGeneration property. See the Customization guide for details.

The generated IsT/AsT properties, Switch/Map methods, and equality members all work with type parameter members the same way they do with concrete types.


Regular unions

While ad hoc unions are quick to set up for combining existing types, regular unions use inheritance to model domain concepts where each case can have its own properties, validation, and behavior.

Regular unions provide more flexibility through inheritance. They're ideal for:

  • Domain modeling with distinct subtypes
  • Complex hierarchies with shared behavior
  • Integration with other features like value objects

Basic implementation

Simple union using inheritance:

[RegularUnion]
public partial class Animal
{
    public sealed class Dog : Animal
    {
        public string Name { get; }

        public Dog(string name) => Name = name;
    }

    public sealed class Cat : Animal
    {
        public string Name { get; }

        public Cat(string name) => Name = name;
    }
}

// Usage
Animal animal = new Animal.Dog("Rover");

// Pattern matching
animal.Switch(
    dog: d => Console.WriteLine($"Dog: {d.Name}"),
    cat: c => Console.WriteLine($"Cat: {c.Name}")
);

Same as above but using records:

[RegularUnion]
public partial record AnimalRecord
{
   public sealed record Dog(string Name) : AnimalRecord;

   public sealed record Cat(string Name) : AnimalRecord;
}

The source generator implements an implicit conversion for every unique constructor parameter type. The generation of the conversion can be customized the same way as with ad hoc unions (see Customizing conversion operators).

Regular unions also support nesting — a derived type can itself be a [RegularUnion] with further sealed subtypes, enabling hierarchical modeling like ApiResponse > Failure > NotFound | Unauthorized. See Nesting Unions in the Customization guide for the full rules.

Domain-specific behavior with abstract methods

Regular unions can encapsulate state-specific behavior using abstract methods on the base class, with each derived type providing its own implementation:

[RegularUnion]
public abstract partial record OrderState
{
    // Behavior specific to the state
    public abstract bool CanCancel();

    public sealed record Pending(DateTime CreatedAt) : OrderState
    {
        public override bool CanCancel() => true; // Can cancel while pending
    }

    public sealed record Shipped(DateTime ShippedAt, string TrackingNumber) : OrderState
    {
        public override bool CanCancel() => false; // Cannot cancel once shipped
    }

   // more states ...
}

// Usage
OrderState currentState = /* get state */;

if (currentState.CanCancel())
{
    // Proceed with cancellation
}

Alternatively, behavior can be implemented externally using the Switch method, which is often preferred for state transitions or operations involving multiple domain objects:

public bool TryCancelOrder(Order order)
{
    return order.CurrentState.Switch(
        pending: _ =>
        {
            order.SetState(new OrderState.Cancelled(DateTime.UtcNow, "Cancelled by user"));
            return true;
        },
        shipped: _ => false, // Cannot cancel

        // handling of other states
    );
}

When to use each approach:

  • Abstract methods: Use when the behavior is inherent to the state itself and requires no external dependencies (e.g., CanCancel(), GetDisplayName()).
  • External Switch: Prefer when the operation involves state transitions, interacts with multiple domain objects, or has cross-cutting concerns like logging or authorization.

Serialization and persistence: Regular unions are polymorphic types. For JSON, apply [JsonDerivedType] attributes to the base class so System.Text.Json includes a $type discriminator. For EF Core, use the standard TPH or TPT inheritance mapping. See Framework Integration for configuration details (including a complete EF Core example) and the Partially Known Date use case below.

Closed hierarchies (C# 15)

C# 15 adds the modifier closed for classes and records. A closed type is implicitly abstract, and the compiler knows all its direct subtypes. The base type of a regular union can be declared closed:

[RegularUnion]
public closed partial record AnimalRecord
{
   public sealed record Dog(string Name) : AnimalRecord;

   public sealed record Cat(string Name) : AnimalRecord;
}

AnimalRecord animal = new AnimalRecord.Dog("Rover");

// The generated Switch/Map methods are available for a closed union as well
animal.Switch(
    dog: d => Console.WriteLine($"Dog: {d.Name}"),
    cat: c => Console.WriteLine($"Cat: {c.Name}")
);

// A switch expression needs no discard arm, because the compiler knows that Dog and Cat are the only cases
var description = animal switch
{
    AnimalRecord.Dog d => $"Dog: {d.Name}",
    AnimalRecord.Cat c => $"Cat: {c.Name}"
};

Console.WriteLine(description);

Requirements:

  • C# 15 and .NET 11. The compiler needs the type System.Runtime.CompilerServices.IsClosedTypeAttribute, which .NET 11 contains. A project with an older target framework gets error CS0656, unless the project declares this attribute itself.
  • closed is optional. A regular union without closed needs neither C# 15 nor .NET 11.

Rules:

  • Write either closed or abstract on the base type. Both together are error CS9384.
  • closed on one partial declaration of the type is enough.
  • The source generator does not add closed. You opt in by writing it.
  • All other rules for regular unions apply to a closed union as well: the cases are nested types, a derived record is sealed, and a derived class is sealed or has private constructors only.

Switch/Map or a switch expression:

Switch and Map stay the recommended default, also for a closed union. A missing handler is a compile error in every project and with every C# version, and the call looks the same as for Smart Enums and ad hoc unions.

A switch expression is a valid alternative for a closed union. It offers patterns and when clauses, and it needs no delegates. Consider these limits:

  • A missing case is only warning CS8509. To turn it into an error, add <WarningsAsErrors>$(WarningsAsErrors);CS8509</WarningsAsErrors> to the project file.
  • The compiler checks switch expressions only. A switch statement with a missing case compiles without a diagnostic.
  • Do not add a discard arm (_ => ...). With a discard arm, the compiler reports no missing case, also when a case is added later.
  • A nullable input (AnimalRecord?) needs an arm for null (warning CS8655).

Nested unions:

In a nested hierarchy with a closed base type ApiResponse, such as ApiResponse > Failure > NotFound | Unauthorized (see Nesting unions), the intermediate type Failure decides what a switch expression over ApiResponse must contain:

  • Failure is closed: the switch expression can list NotFound and Unauthorized, or Failure as a whole.
  • Failure is not closed: the switch expression needs an arm for Failure. Arms for NotFound and Unauthorized alone give warning CS8509.

A record cannot be an intermediate type, also when it is closed (TTRESG055).

Pattern Matching with Switch/Map

For a regular union without a closed base type, the native switch expression of C# does not enforce exhaustive handling of all union cases. Without a default case, the compiler warns that the switch is not complete. However, a discard arm _ => ... that silences the warning hides bugs when new cases are added later:

// Native switch: no compile-time safety when new cases are added
return animal switch
{
    Animal.Dog dog => $"Dog: {dog.Name}",
    Animal.Cat cat => $"Cat: {cat.Name}",
    _ => "Unknown" // Hides unhandled cases: when a new case is added, this arm catches it silently
};

For an ad hoc union, a native switch over the member types does not compile (error CS8121), because a pattern tests the union instance and not its value.

The generated Switch and Map methods solve this. They require a handler for every case in the union, so adding a new type produces a compile-time error at every call site that hasn't been updated.

A regular union with a closed base type (C# 15) is the exception: the compiler checks a switch expression over it. Switch and Map stay the recommended default for such a union as well. See Closed hierarchies (C# 15) for the differences.

An ad hoc union with the union attribute of C# 15 is the second exception: the compiler treats it as a C# union and checks a switch expression over its member types. See Using an ad hoc union as a C# union.

Key Advantages:

  • Compile-time exhaustiveness: Forgetting a case is a compile error, not a runtime bug
  • Type safety: Each handler receives the correctly typed value — no casting needed
  • Readability: Named parameters clearly express which case is being handled

All Switch/Map methods are exhaustive by default, ensuring all cases are handled correctly.

Both Switch and Map come in multiple overloads:

  • Switch (void) accepts an Action per member — use it for side effects with no return value.
  • Switch (with return value) accepts a Func<TResult> per member — use it to compute and return a result.
  • Map accepts a value of TResult per member directly (no lambdas) — a concise shorthand when each member maps to a constant.

IDE Tip: Place the cursor on a Switch, Map, SwitchPartially, or MapPartially call and use the light bulb (Quick Actions) to auto-generate all missing arguments with the correct lambda signatures.

Each of the above also has an overload that accepts an additional state parameter, allowing the use of static lambdas to avoid closure allocations (see Performance: Avoiding Closures below).

Ad hoc union example:

TextOrNumber union = "Hello, World!";

// With "Action"
union.Switch(@string: s => logger.LogInformation("[Switch] String Action: {Text}", s),
             int32: i => logger.LogInformation("[Switch] Int Action: {Number}", i));

// With "Action". Logger is passed as additional parameter to prevent closures.
union.Switch(logger,
             @string: static (l, s) => l.LogInformation("[Switch] String Action with logger: {Text}", s),
             int32: static (l, i) => l.LogInformation("[Switch] Int Action with logger: {Number}", i));

// With "Func<T>"
var switchResponse = union.Switch(@string: static s => $"[Switch] String Func: {s}",
                                  int32: static i => $"[Switch] Int Func: {i}");

// With "Func<T>" and additional argument to prevent closures.
var switchResponseWithContext = union.Switch(123.45,
                                             @string: static (value, s) => $"[Switch] String Func with value: {value} | {s}",
                                             int32: static (value, i) => $"[Switch] Int Func with value: {value} | {i}");

Use Map instead of Switch to return concrete values directly.

var mapResponse = union.Map(@string: "[Map] Mapped string",
                            int32: "[Map] Mapped int");

Regular union example:

Animal animal = new Animal.Dog("Rover");

// With "Action"
animal.Switch(
    dog: d => Console.WriteLine($"Dog: {d.Name}"),
    cat: c => Console.WriteLine($"Cat: {c.Name}"));

// With "Func<T>"
var description = animal.Switch(
    dog: d => $"Dog: {d.Name}",
    cat: c => $"Cat: {c.Name}");

// With "Map"
var label = animal.Map(dog: "Dog", cat: "Cat");

Performance: Avoiding Closures with Static Lambdas

The Switch and Map methods have overloads that accept an additional state/context parameter, allowing you to use static lambdas and avoid closure allocations. This is beneficial in performance-sensitive code paths.

ILogger logger = /* ILogger instance */;

opResult.Switch(
    logger, // Pass logger as state
    success: static (log, s) => log.LogInformation("Success: {Value}", s.Value), // Static lambda
    failure: static (log, f) => log.LogError("Failure: {Error}", f.Error)        // Static lambda
);

Troubleshooting: Return Type Inference in Switch

When using Switch with a return value, all lambdas must return the same type TResult. If they return different-but-compatible types, the compiler cannot infer TResult and marks the entire Switch call as an error — making it hard to spot which lambda is the problem.

For example, this will not compile because List<int> and int[] are different types, even though both are assignable to IReadOnlyList<int>:

// ERROR: The entire Switch call is flagged red
IReadOnlyList<int> result = union.Switch(
    @string: static s => new List<int> { s.Length },
    int32: static i => new int[] { i }
);

Fix: Specify the generic type parameter explicitly. This way, only the lambda with the incompatible return type will be flagged:

// OK: Explicit TResult tells the compiler what to expect
IReadOnlyList<int> result = union.Switch<IReadOnlyList<int>>(
    @string: static s => new List<int> { s.Length },
    int32: static i => new int[] { i }
);

Non-exhaustive overloads for regular unions: For nested union hierarchies, you can generate SwitchPartially/MapPartially overloads that handle intermediate union types as a single case using [UnionSwitchMapOverload]. See Customization for details.

C# 15 unions and Thinktecture unions

C# 15 and .NET 11 add two language features for the same problem: the union declaration (public union Pet(Cat, Dog);) and the modifier closed for class hierarchies. The unions of this library stay supported on every target framework. This section describes how the features relate to each other.

Choosing between a C# union and an ad hoc union

Topic C# union declaration Ad hoc union
Platform C# 15 and .NET 11 Every supported target framework and C# version
Number of case types Not limited 2 to 5
Storage Always a struct with one object? field. A value type is always boxed. Class, struct or ref struct. Typed fields, so a value type is not boxed (unless UseSingleBackingField is set).
Same type twice, stateless members Not possible (a duplicate case type is error CS0111) Supported
==, IEquatable<T>, ToString No == (CS0019). ToString returns the type name. Generated
default Valid and holds null. A switch expression without a null arm throws SwitchExpressionException for it. Compile error TTRESG047 and an exception at run time, or DefaultValueHandling = MapToFirstMember
Access to a case Patterns only. There is no conversion back to a case type. IsX/AsX properties and explicit conversion operators
Exhaustive matching switch expression, checked by the compiler (warning CS8509) Switch/Map. A missing handler is a compile error.
System.Text.Json Built in on .NET 11. The JSON contains the case value without a discriminator, and an ambiguous shape throws JsonException. Object factory
Newtonsoft.Json, MessagePack Not supported Object factory
Entity Framework Core EF Core 11 rejects a property of a union type that has no value converter Object factory with the value converter of this library (EF Core 8 to 11)
ASP.NET Core model binding Request body only Object factory. Route and query values are supported as well.

Rule of thumb:

  • Use a C# union declaration when the case types are reference types, the project targets .NET 11, and pattern matching and System.Text.Json are all you need.
  • Use an ad hoc union when you need value types without boxing, equality, protection against default, the same type twice, stateless members, an older target framework, or one of the framework integrations.
  • Use an ad hoc union with the union attribute of C# when you need an ad hoc union for the reasons above and also want C# patterns on it, and you accept the costs that the next section lists.

Using an ad hoc union as a C# union

The generated code of an ad hoc union has the members that the C# compiler requires of a union type: one public constructor per member type and a public property Value of type object. Add the attribute System.Runtime.CompilerServices.UnionAttribute, and the compiler treats the type as a union:

[AdHocUnion<string, int>]
[System.Runtime.CompilerServices.Union]
public partial struct TextOrNumber;

TextOrNumber textOrNumber = 42;

// The compiler checks that the switch expression handles every member type
var description = textOrNumber switch
{
    string text => $"Text: {text}",
    int number => $"Number: {number}"
};

Console.WriteLine(description); // Number: 42

if (textOrNumber is int value)
    Console.WriteLine(value + 1); // 43

Write the attribute with its namespace. The short form [Union] conflicts with the attribute [Union] of this library (see [RegularUnion], [AdHocUnion] and [Union]).

All generated members stay available: Switch/Map, IsX/AsX, the equality members, the conversion operators and the object factory integration. For a union with the attribute, the source generator adds the members HasValue and TryGetValue. The C# compiler uses them for patterns (see Patterns and boxing). The source generator does not add the attribute. You opt in by writing it.

Requirements:

  • C# 15 and .NET 11. .NET 11 contains the attribute type. A project with an older target framework must declare the type System.Runtime.CompilerServices.UnionAttribute itself.
  • Every project that writes a pattern on the union must compile as C# 15. With an older language version, is null and is not null on such a union are error CS9327. union is { } and union == null compile with every language version.
  • Version 10.7.0 or later of this library. The analyzer rule TTRESG085 and the generated members HasValue and TryGetValue exist since that version. With an older version, the == operator and Equals of a class union with the attribute give wrong results when a member holds null.
  • Default settings for the constructors and for the Value property. See Unsupported configurations (TTRESG085).
  • Prefer a struct. A C# union declaration is always a struct, and the caveats about null below concern classes.

Decision rule: Switch and Map stay the recommended default, also for a union with the attribute. A missing handler is a compile error in every project and with every C# version, and Switch/Map never box. A switch expression is a valid alternative when you need patterns or when clauses. Consider these limits:

  • A missing case is only warning CS8509. Turn it into an error with <WarningsAsErrors>$(WarningsAsErrors);CS8509</WarningsAsErrors> in the project file.
  • Only a switch expression is checked. The compiler does not check a switch statement.
  • Do not add a discard arm (_ => ...), because it hides a member type that is added later.
  • A pattern boxes a value type in some cases, for example in a generic union. See Patterns and boxing.
  • A union with a nullable member needs a null arm (warning CS8655). This applies to a nullable reference type and to a nullable value type such as int?. The null arm cannot tell which member holds null.
  • The default value of a struct union is invalid. Do not use a pattern on it. union is null is true for the default value, so a null arm of a switch expression also receives it. Every other pattern that tests the content either does not match or throws InvalidOperationException, and it is not defined which of the two happens. The run-time protection against the default value covers Value, AsX, Switch and Map. It does not cover patterns. TTRESG047 still reports default(TextOrNumber) at compile time.

Adding the attribute to a public union, or removing it, changes the meaning of patterns in the code that uses the union. It also adds or removes the public members HasValue and TryGetValue, which the compiled patterns of other assemblies call. Treat it as a breaking change of a library.

Pattern semantics

Without the attribute, a pattern tests the union instance. With the attribute, most patterns test the content, which is the value of the current member.

Pattern Without the attribute With the attribute
union is int, union is Cat { Name: "Tom" } Never matches a member type. is gives warning CS0184, and an arm of a switch gives error CS8121. Tests the content
union is null, union is not null (class) Tests the reference Tests the content. is null is also true when the current member holds null.
union is null (struct) Error CS0037 Tests the content
union is object true for every instance false when the content is null
union is { }, union is var x Tests the union instance Tests the union instance
object o = union; o is int false false. A boxed union matches only its own type.

Consequences for a class union:

  • An existing check union is null changes its result when a member can hold null. To test the reference, write union is { }, union == null or ReferenceEquals(union, null).
  • The generated == operator and Equals test the reference, with and without the attribute.

Patterns and boxing

A value of a reference type is never boxed. A value of a value type is boxed when a pattern reads the Value property. To avoid this boxing, the source generator adds two members to a union with the attribute. The C# compiler calls them for patterns instead of Value:

// Generated for TextOrNumber
[EditorBrowsable(EditorBrowsableState.Never)]
public bool HasValue { get; }

[EditorBrowsable(EditorBrowsableState.Never)]
public bool TryGetValue(out string value);

[EditorBrowsable(EditorBrowsableState.Never)]
public bool TryGetValue(out int value);
  • HasValue is true when the union holds a value that is not null. The compiler reads it for is null, is not null and is object.
  • TryGetValue returns true when the union holds a value of the parameter type that is not null. The compiler calls it for a pattern of that type. A member of type int? gets TryGetValue(out int value).
  • Both members carry [EditorBrowsable(EditorBrowsableState.Never)], because they exist for the compiler.

Not every member type gets a TryGetValue method. The table shows when a pattern boxes a value of a value type:

Union or pattern Boxing
Member types that do not convert to each other, for example [AdHocUnion<string, int>] or [AdHocUnion<int, long, Guid>] No
Generic union with a member type that is or contains a type parameter, for example Result<T> with [AdHocUnion<TypeParamRef1, string>] and int as T Yes. Such a union gets no TryGetValue method, because the type parameter can be every type.
Member types that convert to each other by a cast: an interface and a type that implements it ([AdHocUnion<IFormattable, int>]), object, a base class and a derived class Yes. These member types get no TryGetValue method. Another member type of the same union that is distinct gets one.
int together with int? Yes
Pattern for a type that is not a member type, for example union is IComparable Yes
Pattern that needs the value as an object, for example union is object o Yes
Union with UseSingleBackingField = true No. The value is boxed once, when the union is created.

Measured with [AdHocUnion<int, long>]: 100,000 matches of the int member allocate nothing. Without the two members, the same matches allocate 2.4 MB.

Further rules:

  • The two members exist for the compiler. In your own code, use IsX/AsX or Switch/Map. HasValue and TryGetValue describe the value and not the member: when the current member holds null, IsX is true, HasValue is false, and TryGetValue returns false.
  • When you call TryGetValue yourself, write the type of the variable, for example out int number. With out var the call is ambiguous when the union has more than one TryGetValue method (error CS0121).
  • When the union declares or inherits a member with the name HasValue, the source generator generates no HasValue. When the union declares or inherits a member with the name TryGetValue, the source generator generates no TryGetValue method at all. The compiler uses your member when it is public and has the shape shown above. Otherwise the pattern reads Value. A member that the compiler uses is warning TTRESG112 (see Configurations with different semantics (TTRESG112)).
  • The source generator compares the member types by the conversion rules of C#. Arrays with different element types count as distinct types, although the runtime converts some of them into each other (int[] and uint[], an array of an enumeration and the array of its underlying type). A pattern for such an array type matches only a value of the member with that type.

Matching by type and matching by member

A C# pattern uses the runtime type of the value. Switch and Map use the member that the union was created with. The two differ when one member type is convertible to another member type: an interface and a type that implements it, object, a base class and a derived class, or a generic union whose type argument equals another member type.

// int implements IFormattable
[AdHocUnion<IFormattable, int>]
[System.Runtime.CompilerServices.Union]
public partial class FormattableOrNumber;

var union = FormattableOrNumber.CreateIFormattable(5);

var bySwitch = union.Switch(iFormattable: _ => "formattable", int32: _ => "number");

var byPattern = union switch
{
    int => "number",
    IFormattable => "formattable"
};

Console.WriteLine(bySwitch);  // formattable
Console.WriteLine(byPattern); // number

Use the attribute for unions whose member types do not convert to each other. Member types that convert to each other get no TryGetValue method (see Patterns and boxing), so a pattern on them reads Value and keeps matching by the runtime type.

Conversions

For a union type, the compiler adds an implicit conversion from every member type that has a public constructor. This conversion exists also when ConversionFromValue is None or Explicit, and also for an interface member and a type parameter member, for which the library generates no conversion operator. The conversion calls the constructor, so the Normalize methods run as usual.

When a value converts to two member types, the conversion is ambiguous at the place of use (error CS0457). Examples: a class that implements both interfaces of [AdHocUnion<IFirst, ISecond>], or Result<int, int> for [AdHocUnion<TypeParamRef1, TypeParamRef2>]. Use the constructor or the factory method there.

Unsupported configurations (TTRESG085)

The analyzer reports error TTRESG085 at the attribute when the configuration of the ad hoc union does not fit a C# union.

Configuration Problem Fix
ConstructorAccessModifier is not Public A C# union needs public constructors (compiler error CS9385) Use public constructors
ValueMemberName is not Value A C# union needs a public property Value of type object (compiler error CS9386) Keep the name Value
ValueMemberAccessModifier is not Public Same as above Keep the property public
SingleBackingFieldType is set The property Value then has the configured type instead of object (compiler error CS9386) Remove SingleBackingFieldType
A member type occurs more than once A duplicated member type has no public constructor. It is not a case type of the C# union, so a switch expression over the other member types counts as complete and throws SwitchExpressionException for it. Use distinct member types
A stateless member is a reference type (TXIsStateless = true) Its value is always null. The pattern for its type never matches, and is null matches instead. Use a struct as the stateless member type

In all these cases you can also remove the attribute.

Two cases are not reported, because you write the required members yourself:

  • The union implements a public nested interface IUnionMembers (the union member provider of C#). The compiler then takes the creation methods and Value from that interface. The rule for stateless reference types still applies. The case is no TTRESG085, but it is warning TTRESG112 (see Configurations with different semantics (TTRESG112)).
  • ValueMemberName renames the generated property, and you declare a property Value yourself, for example public object? Value => Raw;.

A stateless member type that contains TypeParamRef1 to TypeParamRef5 is not checked.

The attribute is supported only on ad hoc unions. On a regular union, a Smart Enum or a Value Object it is error TTRESG085 as well. For a regular union use a closed base type.

Configurations with different semantics (TTRESG112)

Some configurations compile with the attribute, but the C# compiler treats the union differently from its generated members. For these configurations the source generator reports warning TTRESG112 at the name of the type. The message lists every such configuration of the type.

Configuration What the C# compiler does Fix
ConversionFromValue is None or Explicit The compiler adds an implicit conversion from every member type, so the setting has no effect Remove the setting
A public constructor of your own with one parameter that is passed by value, with in, or as params The parameter type becomes a case type of the C# union. A switch expression over the member types gives warning CS8509 for it. Add a second parameter, make the constructor internal, or use a static factory method
A public instance property HasValue of type bool, declared or inherited The compiler reads your property instead of the content, for example for is null Rename the property
A public instance method bool TryGetValue(out T value) that is not generic, declared or inherited The compiler calls your method for patterns Rename the method
The union implements its public nested interface IUnionMembers The compiler takes the members of the C# union from this interface Remove the interface
A stateless member of type Nullable<T>, for example int? Its value is always null Use a struct that is not Nullable<T> as the stateless member type
A stateless member that is a type parameter without a struct or class constraint Its value is null for a reference type argument Add a struct constraint, or make the member stateful

With a union member provider, TTRESG112 lists only the provider and the stateless members, because the compiler takes all other members from the provider.

In all these cases you can also remove the attribute. When you want the behavior of the C# union, for example with your own HasValue property, suppress TTRESG112 on purpose: with #pragma warning disable TTRESG112, with <NoWarn> in the project file, or with an .editorconfig entry. The warning is reported at the name of the type in the declaration that carries the ad hoc union attribute. A #pragma warning disable TTRESG112 and #pragma warning restore TTRESG112 pair must therefore surround that declaration, and not another partial declaration of the type.

Serialization and Entity Framework Core

An ad hoc union is serialized through an object factory. This does not change with the attribute: when the union has an object factory for System.Text.Json and the Thinktecture JSON converter is in use (the package Thinktecture.Runtime.Extensions.Json, or ThinktectureJsonConverterFactory in the serializer options), the converter of this library is used and the JSON format stays the same.

Without that converter, System.Text.Json of .NET 11 serializes a union with the attribute on its own. Without the attribute a missing converter is visible, because serialization throws. With the attribute it is silent:

  • The JSON contains the value of the member without a discriminator, for example 5 instead of the value of the object factory.
  • The Validate method of an object factory is not called.
  • JSON null gives the default value of a struct union, which is an invalid instance. Serializing such an instance throws InvalidOperationException.
  • Two members that are JSON objects are ambiguous and throw JsonException. With JsonSerializerOptions.Web, which ASP.NET Core uses for request bodies, int and string are ambiguous as well.

System.Text.Json before .NET 11 has no support for union types.

Entity Framework Core 11 rejects a property of a union type that has no value converter ("union types are not supported"). This includes an ad hoc union with the attribute. With a value converter on the property, EF Core 11 accepts the type, with and without the attribute. Without a value converter the model is invalid in both cases, so the attribute does not change what EF Core requires. The value converter of this library meets this requirement: give the union an object factory with UseWithEntityFramework = true and register the value converters of the package Thinktecture.Runtime.Extensions.EntityFrameworkCore11. See Framework Integration.

Thinktecture types and union declarations

  • A Thinktecture attribute on a union declaration is an error (TTRESG083). No code is generated for a union declaration.

  • Smart Enums, Value Objects and unions of this library can be nested in a partial union since version 10.7.0. A containing union without partial is compiler error CS0260, the same as for a containing class. A nested type can be a case type of its container:

    public partial union ProductIdOrNumber(ProductIdOrNumber.ProductId, int)
    {
        [ValueObject<Guid>]
        public partial struct ProductId;
    }
  • A Thinktecture type can be a case type of a union declaration, and a union can be a member type of an ad hoc union ([AdHocUnion<Pet, int>]).

[RegularUnion], [AdHocUnion] and [Union]

Each kind of union has two attribute names:

Union Recommended attribute Other attribute
Regular union [RegularUnion] [Union]
Ad hoc union [AdHocUnion<T1, T2>] (2 to 5 member types) or [AdHocUnion(typeof(T1), typeof(T2))] [Union<T1, T2>] (2 to 5 member types)

Both attributes of a kind have the same settings and generate the same code. [Union] and [Union<T1, T2>] stay supported and are not obsolete. A type must not carry both attributes of a kind. For a regular union this combination is error TTRESG066, for an ad hoc union it is error TTRESG063.

[RegularUnion] and the generic [AdHocUnion<T1, T2>] exist since version 10.7.0. With an older version of the library, use [Union] and [Union<T1, T2>]. There [AdHocUnion<T1, T2>] fails with error CS0308 ("The non-generic type 'AdHocUnionAttribute' cannot be used with type arguments"), and [RegularUnion] fails with error CS0246.

Why [RegularUnion] and [AdHocUnion] are recommended

.NET 11 adds the attribute System.Runtime.CompilerServices.UnionAttribute for the native unions of C# 15. When a project targets .NET 11 and a file imports both Thinktecture and System.Runtime.CompilerServices, the compiler cannot decide which attribute the non-generic [Union] means and reports error CS0104. The error depends on the target framework, not on the language version, so it also appears with LangVersion 14. [RegularUnion] has no such conflict.

The generic [Union<T1, T2>] has no such conflict, because the attribute of .NET has no type parameters. [AdHocUnion<T1, T2>] is recommended for two other reasons. Both forms of an ad hoc union share the name AdHocUnion. A reader cannot confuse the attribute with the [Union] attribute of .NET.

How to switch to the recommended attributes

The analyzer reports the suggestion TTRESG1002 for every [Union] and every [Union<T1, T2>]. The suggestion has the severity Info. Therefore it does not fail a build, also in a project with TreatWarningsAsErrors.

Apply the code fix. It replaces the attributes of both kinds in one step.

  • In Rider or Visual Studio: place the cursor on the attribute and apply the code fix "Replace with 'AdHocUnion'" or "Replace with 'RegularUnion'" of the suggestion TTRESG1002. The fix can be applied to the document, the project or the whole solution.
  • On the command line: dotnet format analyzers --diagnostics TTRESG1002 --severity info.

To switch only one kind, or to switch without the code fix, use search and replace. Replace [Union< with [AdHocUnion<. This replacement is safe, because no other library is known to have a generic Union attribute. For [Union] and [Union( prefer the code fix. A search and replace of these two forms must skip the [Union(...)] attribute of MessagePack-CSharp and the [Union] attribute of .NET 11.

The code fix keeps the type arguments, the attribute arguments and a qualified name such as [Thinktecture.Union<string, int>]. The code fix does not change the following code:

  • typeof(UnionAttribute<,>) and every other usage of the type outside an attribute list. Replace the type with AdHocUnionAttribute<,> by hand.
  • An attribute that is used through a using alias of a constructed type, for example using U = Thinktecture.UnionAttribute<string, int>;.
  • The indentation of attribute arguments that continue on the following lines. The new name is 5 characters longer, so these lines start 5 columns left of the first argument.

Code that looks for an attribute by reflection, for example type.GetCustomAttribute<UnionAttribute>() or typeof(UnionAttribute<,>), must look for RegularUnionAttribute or AdHocUnionAttribute<,> after the switch.

How to keep [Union] and [Union<T1, T2>]

To hide the suggestion TTRESG1002, disable it, for example with dotnet_diagnostic.TTRESG1002.severity = none in .editorconfig. See Suppressing Diagnostics.

In a file with error CS0104 the compiler cannot bind the non-generic [Union]. Therefore the analyzer does not report TTRESG1002 for this attribute, and no code fix is offered. Use one of these fixes:

// 1. Alias in the file
using UnionAttribute = Thinktecture.UnionAttribute;

// 2. Alias for the whole project (in one file of the project)
global using UnionAttribute = Thinktecture.UnionAttribute;

// 3. Full name at the declaration
[Thinktecture.Union]
public abstract partial record OrderState
{
    // ...
}

Alternatively, replace [Union] with [RegularUnion] by hand. The generic [Union<T1, T2>] is not ambiguous.

Further Topics

  • Customization — Property naming, conversion operators, constructors, nullable types, memory optimization, partial matching, equality, nested parameter names, nesting unions
  • Framework Integration — JSON serialization, ASP.NET Core model binding, Entity Framework Core
  • Object Factories — Custom serialization, zero-allocation JSON, ObjectFactoryAttribute<T> configuration
  • Source Generator Configuration — Logging, JetBrains annotations

Real-world use cases and ideas

Discriminated unions are particularly valuable in Domain-Driven Design (DDD) for modeling alternatives within a domain. They enforce invariants at the type level, express ubiquitous language directly in code, and make the different states or variations of a concept explicit. Each case can carry its own specific data and validation rules, preventing invalid states by construction rather than by runtime checks.

Here are some examples I used in the past to show the developers the benefits of discriminated unions.

API Response Handling in Controllers

Ad hoc unions are well-suited for API response handling where the response types already exist and don't share a common class hierarchy:

// Existing response types
public record ProductDto(int Id, string Name, decimal Price);
public record ApiError(int StatusCode, string Message);
public record ValidationFailure(string Field, string Message);

// Ad hoc union combining the possible response types
[AdHocUnion<ProductDto, ApiError, List<ValidationFailure>>]
public partial class GetProductResponse;

A Web API controller can use Switch to transform the union into an IActionResult:

public IActionResult HandleApiResponse(int productId)
{
    GetProductResponse response = GetProductById(productId);

    // Use Switch to convert the union into an IActionResult
    return response.Switch<IActionResult>(
        productDto: product => Ok(product), // HTTP 200 OK with product data
        apiError: error => StatusCode(error.StatusCode, error.Message), // HTTP 404 or 500
        listOfValidationFailure: errors => BadRequest(errors) // HTTP 400 Bad Request
    );
}

Order State Management with Transitions

Regular unions model order lifecycle states where each state carries specific data. The Switch method ensures all states are handled at compile time:

[RegularUnion]
public abstract partial record OrderState
{
    public sealed record New(string CreatedBy) : OrderState;
    public sealed record Processing(DateTime StartedAt, string ProcessedBy) : OrderState;
    public sealed record Shipped(DateTime ShippedAt, string TrackingNumber, string Carrier) : OrderState;
    public sealed record Cancelled(DateTime CancelledAt, string Reason, decimal? CancellationFee) : OrderState;
}

The Order class manages state transitions using Switch:

public record UserPermissions(bool CanShipOrder);

public class Order
{
   private readonly List<OrderState> _states;

   public int Id { get; }
   public OrderState CurrentState => _states[^1]; // Get the last state in the list

   public Order(int id, string createdBy)
   {
      Id = id;
      _states = [new OrderState.New(createdBy)]; // Initial state
   }

   // Method for state transition
   public bool Ship(string trackingNumber, string carrier, UserPermissions userPermissions)
   {
      // Use Switch to determine the outcome
      return CurrentState.Switch(
         processing: _ =>
         {
            // Check permission
            if (!userPermissions.CanShipOrder)
               return false; // User does not have permission to ship this order

            // Change state
            _states.Add(new OrderState.Shipped(DateTime.UtcNow, trackingNumber, carrier));
            return true;
         },
         @new: static _ => false,       // Order must be processed before shipping
         shipped: static _ => false,    // Order has already been shipped
         cancelled: static _ => false); // Cannot ship a cancelled order
   }

   // Gets summary string
   public string GetStatusSummary()
   {
      return CurrentState.Switch(
         @new: static state => $"Order created by {state.CreatedBy}.",
         processing: static state => $"Order processing since {state.StartedAt}.",
         shipped: static state => $"Order shipped on {state.ShippedAt} via {state.Carrier}.",
         cancelled: static state => $"Order cancelled on {state.CancelledAt}: {state.Reason}"
      );
   }
}

Smart Enum + Union Integration (MessageProcessorType)

Different message types (email, SMS, etc.) need different processing logic but should return a uniform result. Here, each MessageProcessorType item holds its own processing delegate (see Smart Enums — Custom methods), and ProcessingResult is a union of Success and Failure.

[RegularUnion]
public abstract partial record ProcessingResult
{
    public sealed record Success(string TransactionId, DateTime Timestamp) : ProcessingResult;
    public sealed record Failure(string ErrorMessage) : ProcessingResult;
}

[SmartEnum<string>]
public partial class MessageProcessorType
{
    public static readonly MessageProcessorType Email = new("EMAIL", ProcessEmail);
    public static readonly MessageProcessorType Sms = new("SMS", ProcessSms);

    [UseDelegateFromConstructor]
    public partial ProcessingResult Process(string message); // Returns a discriminated union

    // Dummy processing logic
    private static ProcessingResult ProcessEmail(string message)
    {
        if (ContainsInvalidCharacter(message))
            return "Email processing failed."; // Failure

        return new ProcessingResult.Success("123", DateTime.UtcNow); // Success
    }

    private static ProcessingResult ProcessSms(string message)
    {
        return new ProcessingResult.Success("123", DateTime.UtcNow); // Success
    }
}

Notice that ProcessEmail returns a string for the failure case — the implicit conversion operator (generated by the union) converts it to ProcessingResult.Failure automatically. Each processor item is self-contained: adding a new processor type (e.g., PushNotification) is a single field declaration with its own delegate, and the Switch on the result ensures all callers handle both outcomes.

Usage:

var processorType = MessageProcessorType.Email;

ProcessingResult result = processorType.Process("Your order shipped!");

// Handle result — compile-time exhaustive
result.Switch(
    success: success => Handle(success.TransactionId, success.Timestamp),
    failure: failure => Handle(failure.ErrorMessage)
);

Partially Known Date

Some use-cases need to handle dates with varying levels of precision. For example, historical dates might only be known by year ("born in 1980") or by year and month ("occurred in June 1995"). The PartiallyKnownDate discriminated union provides an elegant solution to this problem.

[RegularUnion]
public abstract partial record PartiallyKnownDate
{
   public int Year { get; }

   private PartiallyKnownDate(int year)
   {
      Year = year;
   }

   public sealed record YearOnly(int Year) : PartiallyKnownDate(Year);

   public sealed record YearMonth(int Year, int Month) : PartiallyKnownDate(Year);

   public sealed record Date(int Year, int Month, int Day) : PartiallyKnownDate(Year);

   public static implicit operator PartiallyKnownDate(DateOnly dateOnly) =>
      new Date(dateOnly.Year, dateOnly.Month, dateOnly.Day);

   public static implicit operator PartiallyKnownDate?(DateOnly? dateOnly) =>
      dateOnly is null ? null : dateOnly.Value;
}

Usage:

// Date with only year known
var historicalEvent = new PartiallyKnownDate.YearOnly(2000);

// Date with year and month known
var approximateBirthdate = new PartiallyKnownDate.YearMonth(1980, 6);

// Fully known date
var preciseDate = new PartiallyKnownDate.Date(2024, 12, 31);

// Implicit conversion from DateOnly to PartiallyKnownDate
PartiallyKnownDate fullDate = new DateOnly(2024, 3, 15);  // Date(2024, 3, 15)

static string FormatDate(PartiallyKnownDate date)
{
   return date.Switch(
      yearOnly: y => y.Year.ToString(),
      yearMonth: ym => $"{ym.Year}-{ym.Month:D2}",
      date: ymd => $"{ymd.Year}-{ymd.Month:D2}-{ymd.Day:D2}"
   );
}

Console.WriteLine($"Historical event: {FormatDate(historicalEvent)}");              // "2000"
Console.WriteLine($"Approximate birthdate: {FormatDate(approximateBirthdate)}");    // "1980-06"
Console.WriteLine($"Precise date: {FormatDate(preciseDate)}");                      // "2024-12-31"

Jurisdiction

This example demonstrates combining discriminated unions with value objects and smart enums — the union represents the type of jurisdiction, value objects represent the value and rules of each type, and a smart enum models a fixed set of known continents. Jurisdictions can be a country, a federal state, a district, or a continent. Each case enforces its own invariants (ISO code length, non-empty district name), and the "Unknown" state is modeled explicitly within the union rather than relying on null.

[RegularUnion]
public abstract partial class Jurisdiction
{
   [ValueObject<string>(KeyMemberName = "IsoCode")]
   [KeyMemberEqualityComparer<ComparerAccessors.StringOrdinalIgnoreCase, string>] // case-insensitive comparison
   [KeyMemberComparer<ComparerAccessors.StringOrdinalIgnoreCase, string>]
   public partial class Country : Jurisdiction
   {
      static partial void ValidateFactoryArguments(ref ValidationError? validationError, ref string isoCode)
      {
         if (string.IsNullOrWhiteSpace(isoCode))
         {
            validationError = new ValidationError("ISO code is required.");
            isoCode = string.Empty;
            return;
         }

         isoCode = isoCode.Trim();

         if (isoCode.Length != 2)
            validationError = new ValidationError("ISO code must be exactly 2 characters long.");
      }
   }

   /// <summary>
   /// Let's assume that the federal state is represented by an number.
   /// </summary>
   [ValueObject<int>(KeyMemberName = "Number")]
   public partial class FederalState : Jurisdiction;

   [ValueObject<string>(KeyMemberName = "Name")]
   [KeyMemberEqualityComparer<ComparerAccessors.StringOrdinalIgnoreCase, string>] // case-insensitive comparison
   [KeyMemberComparer<ComparerAccessors.StringOrdinalIgnoreCase, string>]
   public partial class District : Jurisdiction;

   /// <summary>
   /// The complex type adds appropriate equality comparison(i.e. it checks for type only).
   /// </summary>
   [ComplexValueObject(SkipFactoryMethods = true)]
   public partial class Unknown : Jurisdiction
   {
      public static readonly Unknown Instance = new();
   }

   /// <summary>
   /// Continent as a Smart Enum — demonstrates combining Smart Enums with unions.
   /// </summary>
   [SmartEnum<string>]
   public partial class Continent : Jurisdiction
   {
      public static readonly Continent Africa = new("Africa");
      public static readonly Continent Antarctica = new("Antarctica");
      public static readonly Continent Asia = new("Asia");
      public static readonly Continent Australia = new("Australia");
      public static readonly Continent Europe = new("Europe");
      public static readonly Continent NorthAmerica = new("North America");
      public static readonly Continent SouthAmerica = new("South America");
   }
}

Usage:

// Creating different jurisdictions
var district = Jurisdiction.District.Create("District 42");
var country = Jurisdiction.Country.Create("DE");
var europe = Jurisdiction.Continent.Europe;
var unknown = Jurisdiction.Unknown.Instance;

// Comparing jurisdictions
var district42 = Jurisdiction.District.Create("DISTRICT 42");
Console.WriteLine($"district == district42: {district == district42}"); // true

var district43 = Jurisdiction.District.Create("District 43");
Console.WriteLine($"district == district43: {district == district43}"); // false

Console.WriteLine($"unknown == Jurisdiction.Unknown.Instance: {unknown == Jurisdiction.Unknown.Instance}"); // true

// Validation examples
try
{
   var invalidJuristiction = Jurisdiction.Country.Create("DEU"); // Throws ValidationException
}
catch (ValidationException ex)
{
   Console.WriteLine(ex.Message); // "ISO code must be exactly 2 characters long."
}

var description = district.Switch(
   country: c => $"Country: {c}",
   federalState: s => $"Federal state: {s}",
   district: d => $"District: {d}",
   continent: c => $"Continent: {c}",
   unknown: _ => "Unknown"
);

Console.WriteLine(description);

If the Jurisdiction must be serialized as JSON then it requires a custom JSON converter. The converter needs to know the type of the object to be serialized. This can be achieved by using a Smart Enum as a discriminator (JurisdictionJsonConverter).

Clone this wiki locally