A discriminated union is a data structure that can hold one of several distinct types of data. This type-safety allows developers to build complex data structures, like API responses or state machine events, and ensures all possible cases are handled, preventing runtime errors.

This is a proposal that might come in C# 16

If you prefer this as a video explanation then Nick Chapsas made one: https://www.youtube.com/watch?v=tD46WVJ2h9I

all 2 comments

sorted by: hot top controversial new old
[–] 1 point 1 year ago

Looking good. Especially looking forward to unions backed by a struct.

  • source
  • [–] 1 point 1 year ago* (last edited 1 year ago)

    This exactly what I described in 2021, so I'm pretty happy seeing other languages also going this route.

    Sadly, they also don't have a solution for the follow-up question that naturally falls out if this approach -- how to "unbox" generic types such that they can be used directly and don't need some additional type to hold it, i.e.

    union Option[T] of T, None // None defined elsewhere
    

    instead of

    union Option[T] of Some[T], None // Some & None defined elsewhere
    
  • source