What are Discriminated Unions?

Discriminated Unions allow us to tell the compiler that data can be ONE OF A RANGE of pre-defined types.

A union class is declared similar to an enum, except each member is a type that itself can hold state in one or more state variables.

In the example below U can be returned from a method and can be any of A, B or C.

union U
{
A(int x, string y);
B(int z);
C;
}


DUs will typically help us with our return types when sometimes we might have a success condition and in others we will have error conditions, but currently we have NO ELEGANT AND STRONGLY TYPED way to inform the method consumers of this.

Potential use case example below …


And this is how the method might look with Discriminated Unions applied with the OneOf library :


DUs don’t currently exist in C# at the moment but are coming soon, so we’ll be able to use them natively without needing third-party libraries like OneOf.

Leave a Reply

Your email address will not be published. Required fields are marked *