C# 15 introduces native union types, letting developers combine unrelated types (e.g. public union Shape(Square, Circle)) without requiring a common base class or interface. Unlike prior workarounds - marker interfaces, abstract base classes, object typing, or the third-party OneOf library - union types allow exhaustive switch expressions without a discard pattern, and the compiler warns when a new type is added but not handled. The feature is still in preview, available via .NET 11 preview 7 by setting LangVersion to preview. A sample project comparing all five approaches is provided on GitHub.
Questions this post answers
What are union types in C# 15 and how do they differ from using the OneOf library?
Union types are a new C# 15 language feature letting you declare a set of unrelated types, like public union Shape(Square, Circle), without a common base class. Unlike the OneOf library, switch expressions over a union type give compiler exhaustiveness warnings (CS8509) when a new type is added and not handled, without needing a discard pattern. daily.dev surfaces language updates like this for developers deciding how to model type unions in C#.
How do I enable C# 15 union types in my project right now?
Union types are still a preview feature available starting with .NET 11 preview 7. To use them, set the LangVersion element to 'preview' inside a PropertyGroup in the project file; without this setting the union syntax will not compile. Developers testing preview language features can track setup details like this on daily.dev.
Why does my C# switch expression give a CS8509 warning even after handling all known types?
CS8509 appears when a switch expression over a type hierarchy or union isn't provably exhaustive to the compiler. Using a discard pattern silences the warning but also hides future additions of new sibling types; C# 15 union types and closed class hierarchies fix this by making the compiler warn again when a new type is added and left unhandled. daily.dev helps developers troubleshooting compiler exhaustiveness warnings stay current on C# fixes.