Tip #005
Union types in C# 15
About this tip
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.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffeeCode
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.csRex says woof