2 ms·
> Oh, to have Either / Discrimated Unions in C# :( Here you go: https://sourceforge.net/p/sasa/code/ci/dotnet-standard/tree/Sasa/Either.cs https://sourceforge.
by naasking 9y ago
> Oh, to have Either / Discrimated Unions in C# :(
Here you go: https://sourceforge.net/p/sasa/code/ci/dotnet-standard/tree/Sasa/Either.cs https://sourceforge.net/p/sasa/code/ci/dotnet-standard/tree/...
You can use it like:
Either<string, int> x = 99;
if (x.TryCase1(out var s))
...
else if (x.TryCase2(out var i))
...
Only up to 4 cases are included because beyond that, I think you should define a custom type.
- naasking 9y agoAlthough I should note that C# now supports special casting via the 'is' operator, so you can now just do this: object x = 99; if (x is string s)) ... do something with 's' else if (x is int i)) ... do something with 'i'
- coldacid 9y agoThere's also the OneOf NuGet package [1] which I've put to good use in a number of projects. Using `object` and `is` means you can't enforce what types get passed in, nor can you ensure that all possible types actually get handled. [1]: https://github.com/mcintyre321/OneOf/ https://github.com/mcintyre321/OneOf/
- naasking 9y agoI can never justify the use of delegates for pattern matching purposes. It's just way too much overhead, and so would discourage the use of these abstractions.