skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Union types in C# 15

C# 15

Code card declaring a C# 15 Pet union of Cat, Dog and Bird, then switching on a Dog. Output: Rex says woof.

A union declares a closed set of case types. The compiler warns (CS8509) when a switch misses a case. C# 15 ships union types in .NET 11. Declare union Pet(Cat, Dog, Bird) and the compiler checks that your switch covers every case. Drop Bird and you get CS8509 "'Bird' is not covered". Run it with the .NET 11 SDK. It is new in C# 15. The key line is union Pet(Cat, Dog, Bird) in pets.cs. Run it and the output reads Rex says woof.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
pets.cs
Pet pet = new Dog("Rex");
var sound = pet switch
{
Cat c => $"{c.Name} says meow",
Dog d => $"{d.Name} says woof",
Bird b => $"{b.Name} says tweet",
};
Console.WriteLine(sound);
record Cat(string Name);
record Dog(string Name);
record Bird(string Name);
union Pet(Cat, Dog, Bird);
Output
$ dotnet run pets.cs
Rex says woof