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

  • soc@programming.dev
    link
    fedilink
    English
    arrow-up
    1
    ·
    edit-2
    4 days 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