meetings/working-groups/discriminated-unions/Trade Off Matrix.md
There are only three possible ways to represent a type that behaves like a discriminated union or type union in C# without a large runtime overhaul.
// example: a record hierarchy
public abstract record MyUnion
{
public record Case1(...) : MyUnion;
public record Case2(...) : MyUnion;
public record Case3(...) : MyUnion;
}
MyUnion union = new MyUnion.Case1(...);
object union; // only assign Case1, Case2 or Case3 here please.
...
union = new Case1(...);
// example: a struct wrapper with constructors and a value property
public struct MyUnion
{
public MyUnion(Case1 value) {...}
public MyUnion(Case2 value) {...}
public MyUnion(Case3 value) {...}
public object Value { get; }
}
MyUnion union = new MyUnion(new Case1(...));
These are exactly what developers use when defining the equivalent of discriminated unions and type unions in C# code today.
However, none of these user defined solutions allow for exhaustiveness in pattern matching, because they are either too open ended or not understood as being closed by the runtime and language.
The following proposals offer solutions for exhaustiveness and more, with a matrix of trade-offs between them.
Closed Hierarchies proposal offers an easy way to make class hierarchies closed.Runtime Type Unions proposal offers a special kind of object reference that is understood by the runtime.Nominal Type Unions proposal offers a wrapper type solution understood by the language.| Feature | Runtime Type Unions | Nominal Type Unions | Closed Hierarchies |
|---|---|---|---|
| Declared Cases | Yes | Yes | Yes |
| Singleton Cases | Yes | Yes | Yes |
| Existing Cases | Yes | Yes | |
| Anonymous Syntax | Yes | ||
| Pattern Matching | Yes | Yes | Yes |
| Dynamic Pattern Matching | Yes | Yes | |
| Subtype Relationship | Yes | ||
| Conversion Relationship | Yes | Yes | |
| Back-Compat | Yes | Yes | |
| Non-ABI Breaking | named only | Yes | Yes |
| Non-Allocating/Boxing | future | ||
| Custom Unions | future | ||
| Any Time Soon | Yes | Yes |