-
Notifications
You must be signed in to change notification settings - Fork 0
/
Result.cs
38 lines (28 loc) · 1.46 KB
/
Result.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Result
{
public bool IsFailure => !IsSuccess;
public bool IsSuccess { get; }
public Error Error { get; }
public StackTrace? StackTrace { get; init; }
protected internal Result(bool isSuccess, Error error, StackTrace, stackTrace)
{
if (isSuccess && error != Error.None || !isSuccess && error == Error.None)
{
throw new InvalidOperationException(nameof(error));
}
(IsSuccess, Error, StackTrace) = (isSuccess, error, stackTrace);
}
public static Result Success() => new(true, Error.None);
public static Result Failure(Error error) => new(false, error, new StackTrace());
public static Result<TValue> Success<TValue>(TValue value) => new(value, true, Error.None);
public static Result<TValue> Failure<TValue>(Error error) => new(default, false, error, new StackTrace());
public static Result<TValue> Create<TValue>(TValue? value) => value != null ? Success(value) : Failure<TValue>(Error.NullValue);
}
public class Result<TValue> : Result // generic Result<T> class
{
private readonly TValue? _value;
protected internal Result(TValue? value, bool isSuccess, Error error) : base(isSuccess, error) => _value = value;
public static implicit operator Result<TValue>(TValue? value) => Create(value);
public TValue Value => IsSuccess ? _value! : throw new InvalidOperationException(
"The value of a failure result can not be accessed.");
}