Microsoft devs rejoice: Union types coming to C# in November
Microsoft is set to launch the next iteration of C# this November.
Redmond recently unveiled a preview of C# 15 that introduces tighter restrictions on data types alongside enhanced memory safety protections.
Perhaps the most frequently requested feature that arrives with this release is union types.
Union types are not new to programming.
Python, Scala and TypeScript all recognize the concept.
But with C#, “This is how unions should be,” boasted C# lead designer Mads Torgersen in an introductory talk earlier this year.
In a nutshell, union types provide a way to categorize different custom data types into a single entity.
The union keyword can unite a collection of custom data types (“Dog,” “Cat,” and “Bird”) as a single umbrella type, such as “Pet.” The union keyword gives the compiler a definitive list of “pets,” which can’t be expanded.
“Unions enable designs that traditional hierarchies can’t express, composing any combination of existing types into a single, compiler-verified contract,” explained the Microsoft documentation.
Upsides for developers include better pattern matching, the ability to write custom functions for union types, protection against rogue data types, stronger abstractions, and less writing of boilerplate error code.
In his talk, Torgersen, along with Microsoft principal engineer Dustin Campbell, demonstrated how a union could consolidate two different records for designating the success or failure of an input stream over a network.
They presented two separate record types: one indicating success using an integer, the other a standard text error message.
By grouping them using the union keyword, they created a single switch expression to parse the results.
Without this shortcut, they would have had to add an error message to their switch statement to handle unknown input, create a wrapper (which would have used more memory and probably would have been buggier), or deploy a third-party library to parse the results.
5News aggregated this summary from the outlet’s public feed. The full article, with all the context, is on www.theregister.com — the content belongs to The Register.