OneOf is a C# library that implements discriminated unions, allowing methods to return one of several predefined types in a type-safe manner. Unlike tuples that bundle multiple values together, OneOf represents a choice between types (A or B or C), with compiler-enforced exhaustive handling through the .Match() method. The library provides a cleaner alternative to exception-driven control flow, inheritance hierarchies, and marker interfaces. Common use cases include polymorphic return types without inheritance, state machines with rich data per state, multi-channel notifications, file format handling, and explicit error handling. The approach makes failures explicit in method signatures, improves code readability, and eliminates entire categories of bugs by forcing developers to handle all possible cases at compile time.
Table of contents
Table of ContentsWhat is OneOf?Installing OneOfCore Concepts And FunctionalityA Solution to Exception-Driven Control FlowOneOf Provides a Cleaner AlternativeWhen to Still Use Exceptions:Other OneOf Use CasesKey Benefits of OneOfConclusionSort: