
C15 Union Types in .NET 11: Say Goodbye to Type Unwrapping
C# 15 Union Types in .NET 11: Say Goodbye to Type Unwrapping If you've been waiting for one of the most requested C# features, it's finally here. Microsoft introduced Union Types in C# 15, part of the upcoming .NET 11 SDK currently in Preview 2. What Are Union Types? A union type allows a variable to hold one value from a closed set of multiple types. Think of it as a compile-time safer alternative to object or dynamic when you specifically need a type that could be A, B, or C. The Old Way Before union types, we had to deal with type unions like this: // Painful type checking object value = GetValue (); if ( value is string str ) { Console . WriteLine ( str . ToUpper ()); } else if ( value is int num ) { Console . WriteLine ( num * 2 ); } else if ( value is DateTime date ) { Console . WriteLine ( date . ToShortDateString ()); } The Union Type Way With union types in C# 15, it becomes elegantly simple: // Declare a union type ValueWithUnion < string | int | DateTime > result = GetValue
Continue reading on Dev.to
Opens in a new tab
