In a previous post, “.NET 11 Preview - Discriminated Unions Support”, we looked at the support for discriminated union types in .NET.

To recap. let us declare some types:

public record class Human(string Name);

public record class Animal(string Name, int Legs);

public record class Bird(string Name, int Wings);

We want to write a method that can greet any of these types.

This is where the union comes into play:

public union LivingThing(Human, Animal, Bird);

Then we write our method:

string Greet(LivingThing livingThing)
{
    return livingThing switch
    {
        Human human => $"I am {human.Name}, a human",
        Animal animal => $"It seems I am {animal.Name}, a animal",
        Bird bird => $"I am a bird of {bird.Name}"
    };
}

Finally, create some types and invoke our method:

var man = new Human("James Bond");
var chicken = new Bird("Chicken", 2);
var dog = new Animal("Dog", 2);

Console.WriteLine(Greet(man));
Console.WriteLine(Greet(dog));
Console.WriteLine(Greet(chicken));

This works as expected.

unionRun

This feature was a preview, and required the following entry in your .csproj project file:

<LangVersion>preview</LangVersion>

As of the release candidate, this is no longer required, as unions now are fully supported features.

TLDR

Unions are now native supported in .NET 11.

The code is in my GitHub.

Happy hacking!