using System; namespace SessionCompanion.Extensions.EitherType { public class Either { 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; } /// /// Bazowa metoda dopasowania wzorów. /// Jeśli podana jest wartość lewa, to Match zwróci wynik lewej funkcji, w przeciwnym razie wynik prawej funkcji. /// /// /// Lewa funkcja /// Prawa funkcja /// Wynik prawej/lewej funkcji public T Match(Func leftFunc, Func rightFunc) { if (leftFunc == null) { throw new ArgumentNullException(nameof(leftFunc)); } if (rightFunc == null) { throw new ArgumentNullException(nameof(rightFunc)); } return this.isLeft ? leftFunc(this.left) : rightFunc(this.right); } public void DoRight(Action rightAction) { if (rightAction == null) { throw new ArgumentNullException(nameof(rightAction)); } if (!this.isLeft) { rightAction(this.right); } } public TL LeftOrDefault() => this.Match(l => l, r => default(TL)); public TR RightOrDefault() => this.Match(l => default(TR), r => r); public static implicit operator Either(TL left) => new Either(left); public static implicit operator Either(TR right) => new Either(right); } }