C#

Discriminated unions before C# 15: the workarounds

Maarten Balliauw Maarten Balliauw
C#

Maarten Balliauw explains how C# developers faked discriminated unions before C# 15: the implicit-operator trick behind ASP.NET Core's Results<>, the OneOf package and plain F#. A useful read if you want compiler-checked return types in your own code today.

Key points

  • Results<TResult1, TResult2, TResult3> fakes a union with one implicit operator per supported type.
  • You can copy the class into your own code and return Results<int, bool, string> from a method.
  • Returning a type outside the declared set produces a compiler and IDE error.
  • The gap: switch expressions get no exhaustiveness check when you add a fourth type.
  • In Minimal APIs Results<> is enough, since the framework consumes the result for you.
  • Outside Minimal APIs, the OneOf package or F# gives real discriminated unions.

Real-world use

  • Guaranteeing a Minimal API endpoint only returns allowed results such as Ok and Unauthorized.
  • Stopping a RegisterUser() method from returning anything but User, UserAlreadyExists or InvalidUsername at compile time.

This summary was generated by the agent from the original post on Maarten Balliauw. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message