namespace Drab.Core.Models; public class Result { private TBad _error; private TOk _ok; public bool IsOk { get; } public bool IsNotOk => !IsOk; public Result(bool isOk, TOk ok, TBad bad) { IsOk = isOk; if (IsOk) { if (ok == null) throw new ArgumentNullException(nameof(ok), "If IsOk flag is set to true parameter 'ok' needs to be non null"); Value = ok; } else { if (bad == null) throw new ArgumentNullException(nameof(bad), "If IsOk flag is set to false parameter 'bad' needs to be non null"); Error = bad; } } public TBad Error { get { if (IsOk) throw new InvalidOperationException("Result has IsOk flag set to true only Value property is available"); return _error; } private set => _error = value; } public TOk Value { get { if (!IsOk) throw new InvalidOperationException("Result has IsOk flag set to false only Error property is available"); return _ok; } private set => _ok = value; } public Result Map(Func map) where TNew : class { if (IsOk) return new Result(IsOk, map(Value), default); else return new Result(false, default, Error); } public TOk ValueWithDefault(Func defaultCreator) => IsOk ? Value : defaultCreator(Error); public void Do(Action action) { if (IsOk) action(Value); } } public class Result { public static Result Failed(TK wrong) { return new Result(false, default(T), wrong); } public static Result Ok(T ok) { return new Result(true, ok, default(TK)); } }