Skip to content

Instantly share code, notes, and snippets.

@mike-kilo
Created March 23, 2021 10:06
Show Gist options
  • Save mike-kilo/2613a417bfd461e349849ce7b7441cd8 to your computer and use it in GitHub Desktop.
Save mike-kilo/2613a417bfd461e349849ce7b7441cd8 to your computer and use it in GitHub Desktop.
Either - like in F#
using System;
namespace Helpers
{
public class Either<TL, TR>
{
private readonly TL left;
private readonly TR right;
private readonly bool isLeft;
public Either(TL left)
{
this.left = left;
this.isLeft = true;
}
public Either(TR right)
{
this.right = right;
this.isLeft = false;
}
public T Match<T>(Func<TL, T> leftFunc, Func<TR, T> rightFunc) => this.isLeft ? leftFunc(this.left) : rightFunc(this.right);
public Either<TL, TR> InvokeOn<T>(T param, Func<TL, T, TL> leftFunc, Func<TR, T, TR> rightFunc) => this.isLeft ? new Either<TL, TR>(leftFunc(this.left, param)) : new Either<TL, TR>(rightFunc(this.right, param));
public Either<TL, TR> InvokeOn<T>(T[] param, Func<TL, T[], TL> leftFunc, Func<TR, T[], TR> rightFunc) => this.isLeft ? new Either<TL, TR>(leftFunc(this.left, param)) : new Either<TL, TR>(rightFunc(this.right, param));
public bool IsOfType(Type t) => this.isLeft && typeof(TL).Equals(t) || !this.isLeft && typeof(TR).Equals(t);
public static implicit operator Either<TL, TR>(TL left) => new Either<TL, TR>(left);
public static implicit operator Either<TL, TR>(TR right) => new Either<TL, TR>(right);
public static implicit operator TL(Either<TL, TR> e)
{
if (e.isLeft == true) return e.left;
throw new InvalidCastException($"This object is not of type {typeof(TL).ToString()}");
}
public static implicit operator TR(Either<TL, TR> e)
{
if (e.isLeft == false) return e.right;
throw new InvalidCastException($"This object is not of type {typeof(TR).ToString()}");
}
}
}
@mike-kilo
Copy link
Author

Copied from https://github.com/mikhailshilkov/mikhailio-samples/blob/1456e4ad61db1d0ae633f9262218aa09a9fda645/Either%7BTL,TR%7D.cs and extended with couple of new methods (casting, method invoke, etc.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment