This library introduces a powerful mechanism for discriminated type unions in .NET 8 through two main constructs: OneOf and Result/Results. Both these constructs can work with up to 6 type arguments (T0, T1, ... T5).
The core concept of the library. Represents a choice between one of the given types.
- Basic usage
OneOf<string, int> union;
union = "Operation is successful";
Console.WriteLine(union); // >> Operation is successful
union = 42;
Console.WriteLine(union); // >> 42
- Equality Check
OneOf<bool, int, string> unionA = 42;
OneOf<bool, int, string> unionB = 42;
bool isMatch = unionA == unionB;
Console.WriteLine(isMatch); // >> True
- Matching Values
OneOf<int, string, Exception> union = "Some text";
string result = union.Match
(
number => number.ToString(),
text => text.ToUpperInvariant(),
error => error.Message
);
Console.WriteLine(result); // >> SOME TEXT