OneOf for C#: F#-Style Discriminated Unions with Exhaustive Matching
Easy to use F#-like ~discriminated~ unions for C# with exhaustive compile time matching
At a glance
- What is it?
- OneOf is a NuGet library that gives C# developers a discriminated union type with compile-time exhaustive matching. It suits teams replacing exception-driven control flow or IActionResult return types with typed result objects.
- Who is it for?
- Adopt OneOf if your team writes C# and wants typed method signatures that force callers to handle every outcome, particularly around validation and error returns where a custom base type or IActionResult is currently used. Skip it if your codebase is already F# or if your result types are consumed by serialization frameworks that cannot express a generic union without custom converters.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 49 days ago.
- What is it written in?
- Mainly C#, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on November 15, 2026, and from our analysis. They are not legal advice.
Star history
- mcintyre321/OneOf4,060 ★ · +4
| Repository | 2026-09-24 | 2026-11-15 |
|---|---|---|
| mcintyre321/OneOf | 4.1k | 4.1k |
4 Stars in the last 52 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
The problem OneOf addresses in C# codebases
C# has no built-in discriminated union. The common workarounds are a custom result base class, a non-descriptive return type such as object, or exceptions used for control flow. Each of these pushes the set of possible outcomes out of the method signature and into documentation or runtime behaviour. The README quotes a user describing the library as a "compile time checked switch statement", which is a fair summary of the intent.
The library targets developers who want a method signature to state exactly which outcomes are possible and who want the compiler to reject callers that ignore one. It is most useful in validation and command-handling code, where a method might return a success value or one of several typed failure objects. The README's own example is an MVC controller action returning OneOf<User, InvalidName, NameTaken>.
This is not a general-purpose replacement for inheritance. It is a replacement for the specific pattern where a base type gains an abstract method and every derived type implements it. The README frames exhaustive matching as an alternative to polymorphism in exactly that case.
How OneOf represents a value and how Match enforces exhaustiveness
OneOf<T0, ... Tn> holds a single value that is one of the types in its generic argument list. The number of generic parameters is fixed at the declaration site, and the matching API mirrors that count. The Match method takes one Func per generic argument and returns a single value of type TOut. Switch does the same work when no value is returned.
The exhaustiveness guarantee comes from the arity of the delegate list. There is no default handler, so a caller cannot silently ignore a case. The README states that if you add another generic parameter, you have to update all the calling code. In brownfield code, that is the point: the default handler in a switch statement is often a runtime throw or behaviour that does not suit the new result type.
TryPick methods offer a different access pattern. For OneOf<T0, T1, T2>, each TryPickT𝑥 returns a bool, sets an out value when the union holds that type, and otherwise sets a remainder that is a OneOf of the remaining types. The README's example chains TryPickT1 twice to peel a NotFound case off a OneOf<Thing, NotFound, Error> and then an Error case off the remainder. Note that after the second pick, the variable is a Thing rather than a OneOf<Thing>.
Installing OneOf and writing a first exhaustive match
The README gives one installation instruction, the NuGet Package Manager console command shown below. The package is published on NuGet under the name OneOf. There is no separate CLI or service to run.
install-package OneOfOnce the package is referenced, the smallest useful step is to declare a union as a method return type and match on it at the call site. The following is adapted from the README's controller example, with the repository and model types left out so the shape of the API is visible.
Reusable union types with OneOfBase and source generation
Declaring OneOf<T0, T1> inline at every method signature gets repetitive. OneOfBase lets you define a named type that inherits the Match, Switch and TryPick𝑥 methods. The README's example is a StringOrNumber class deriving from OneOfBase<string, int>, with implicit conversions from string and int so call sites stay readable.
The derived type can also add members. The README defines TryGetNumber on StringOrNumber, implemented with Match, returning a tuple of a bool and an int. That pattern is how you attach domain behaviour to a union without losing the exhaustive match inside the derived class.
The repository also contains a source generator, contributed according to the README by a user named @romfir. It generates OneOfBase hierarchies from a GenerateOneOfAttribute applied to a partial class. Treat the generator as a separate adoption decision from the core library.
Where OneOf is the wrong tool
The arity is fixed at compile time. A union of three types cannot be widened to four without touching every Match call. That is the advertised benefit, but it is also a real cost in code that evolves quickly or in libraries that expose the union across a public API boundary. Consumers of your package will have to recompile against the new arity.
OneOf is also a poor fit for serialization-heavy boundaries. The README does not document JSON converters, model binding or any integration with System.Text.Json or Newtonsoft.Json. A OneOf value passed to a serializer has no documented representation. If your return values cross an HTTP boundary as payloads rather than being matched server-side, you will need to decide how the union is projected, and the repository does not answer that for you.
Finally, the library does not replace F#. If your project is already F#, the language has discriminated unions natively, and adding a C#-oriented union type would be redundant.
How OneOf differs from returning a result base class
The most direct alternative is a hand-written result base class with one derived type per outcome, which is what many C# codebases already have. The difference is where exhaustiveness is enforced. With a base class, a switch over the derived types can omit a case and still compile; the compiler has no way to know the set is closed. With OneOf, the Match delegate list has a fixed arity, so a missing case is a compile error. The README states this directly when it says the number of handlers matches the number of generic arguments.
A second difference is allocation and type identity. A base class hierarchy typically means one class per outcome and reference equality checks. OneOf is a generic wrapper whose behaviour depends on the implementation inside the OneOf package, which the README does not describe in detail. If you are choosing between the two on performance grounds, the README gives you nothing to decide with, and you should read the source in the OneOf directory of the repository before assuming either is cheaper.
A third difference is visibility. A base class can be extended by consumers unless you seal it. A OneOf<T0, T1> is closed by construction, which is usually what you want in an internal API but can be restrictive in a public one.
Maintenance, licensing and the cost of upgrading
The repository is not archived, and the last push was on 2026-06-11. The repository has no published GitHub releases, and the README does not describe a versioning or deprecation policy. Plan for upgrades as source-level changes rather than as a documented migration path.
The practical upgrade cost is concentrated in arity changes. Adding or removing a generic parameter from a union that is used widely will surface as compile errors at every Match and Switch call site. That is a feature, but it means the blast radius of a union change is proportional to its usage, and you should size that before introducing a union into a shared library.
OneOf is licensed under MIT, per the licence.md file in the repository and the licence badge in the README. MIT permits commercial use and modification with the licence and copyright notice retained. This is a factual description of the licence text, not legal advice; if your organisation has specific obligations around attribution or dependency review, route the licence file through your normal process.
Editorial conclusion
Adopt OneOf if your team writes C# and wants typed method signatures that force callers to handle every outcome, particularly around validation and error returns where a custom base type or IActionResult is currently used. Skip it if your codebase is already F# or if your result types are consumed by serialization frameworks that cannot express a generic union without custom converters. Before committing, verify that your target framework supports the Source Generator path you intend to use, and confirm how OneOfBase interacts with your existing DI and serialization layers, since the README does not document those integrations.
Frequently asked questions
How do you install OneOf in a C# project?
The README gives the NuGet Package Manager console command install-package OneOf. The package is published on NuGet under the name OneOf, and there is no separate CLI or service to run.
What is the difference between Match and Switch in OneOf?
Match takes one Func per generic argument and returns a value of type TOut, while Switch is used when you are not returning a value. Both require a handler for every type in the union.
Can you reuse a OneOf type instead of declaring it inline?
Yes. You can derive from OneOfBase, as the README shows with a StringOrNumber class over OneOfBase<string, int>, and the derived class inherits Match, Switch and TryPick. You can also add your own members, such as the TryGetNumber method in the README example.
Does OneOf support source generation for union types?
The repository contains a source generator, and the README mentions generating OneOfBase hierarchies with GenerateOneOfAttribute and a partial class.
What happens when a new type is added to a OneOf union?
The README states that there is no fallback: if you add another generic parameter, you have to update all the calling code to handle the change. That is presented as an advantage over switch statements, which can silently fall through to a default handler.
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/mcintyre321-oneof)Star history chart for your README
[](https://hysenlabs.com/projects/mcintyre321-oneof)Was this useful?