using System; namespace JobsJobsJobs.Shared { /// /// A result with two different possibilities /// /// The type of the Ok result public struct Result { private readonly TOk? _okValue; /// /// Is this an Ok result? /// public bool IsOk { get; init; } /// /// Is this an Error result? /// public bool IsError { get => !IsOk; } /// /// The Ok value /// public TOk Ok { get => _okValue!; } /// /// The error value /// public string Error { get; set; } /// /// Constructor (inaccessible - use static creation methods) /// /// Whether this is an Ok result /// The value of the Ok result /// The error message of the Error result private Result(bool isOk, TOk? okValue = default, string error = "") { IsOk = isOk; _okValue = okValue; Error = error; } /// /// Create an Ok result /// /// The value of the Ok result /// The Ok result public static Result AsOk(TOk okValue) => new Result(true, okValue); /// /// Create an Error result /// /// The error message /// The Error result public static Result AsError(string error) => new Result(false) { Error = error }; /// /// Transform a result if it is OK, passing the error along if it is an error /// /// The transforming function /// The existing result /// The resultant result public static Result Bind(Func> f, Result result) => result.IsOk ? f(result.Ok) : result; /// /// Transform a result to a different type if it is OK, passing the error along if it is an error /// /// The type to which the result is transformed /// The transforming function /// The existing result /// The resultant result public static Result Map(Func> f, Result result) => result.IsOk ? f(result.Ok) : Result.AsError(result.Error); } }