C# 15 just introduced union types and this is a big deal for .NET developers. Instead of using object, marker interfaces, or abstract base classes to represent "one of several types," you can now write: public union Pet(Cat, Dog, Bird); What makes this powerful: → Closed set of types — no unexpected additions → Compiler-enforced exhaustive pattern matching → No common base class required — union of completely unrelated types → Works with generics (OneOrMore<t> anyone?) The compiler catches missing cases at build time, not runtime. If you add a new case type, every switch that doesn't handle it gets a warning. If you've used discriminated unions in F# you'll feel right at home. But this is designed to feel native to C#. Available now in .NET 11 Preview 2. What pattern would you use this for first? #dotnet #csharp #programming #softwaredevelopment
> a big deal for .NET developers. You mean for C# developers. F# had union types since 2005 😊
Lol beautiful but... but... but... F#
Remember 15 is a inbetween rerelease this might change in 16
The "animal" example has minimal impact for me (there are better patterns). But:public union FuncResult(ResData, ErrorDesc)can be very useful to return actual computed data or a full error description class.
I think unions will really shine when combined with switch expressions, because with it you can switch between the multiple types with simple, concise test expressions. Thanks for sharing
I’d probably start with API response models.. handling success, validation errors, and failures in a type-safe way instead of relying on loosely structured responses.
Woooow this is BIG! I personally really love F# and have wondered if we ever would get union types in C#! This is just amazing! Can't wait to play around with it
Full blog post from Bill Wagner: https://devblogs.microsoft.com/dotnet/csharp-15-union-types/