Last active
March 18, 2020 17:11
-
-
Save 1saeedsalehi/af1d65e9668220f44e80c6c28b9e3019 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Exceptions | |
{ | |
public class Result | |
{ | |
public bool IsSuccess { get; } | |
public string Error { get; } | |
public bool IsFailure => !IsSuccess; | |
protected Result(bool isSuccess, string error) | |
{ | |
if (isSuccess && error != string.Empty) | |
throw new InvalidOperationException(); | |
if (!isSuccess && error == string.Empty) | |
throw new InvalidOperationException(); | |
IsSuccess = isSuccess; | |
Error = error; | |
} | |
public static Result Fail(string message) | |
{ | |
return new Result(false, message); | |
} | |
public static Result<T> Fail<T>(string message) | |
{ | |
return new Result<T>(default(T), false, message); | |
} | |
public static Result Ok() | |
{ | |
return new Result(true, string.Empty); | |
} | |
public static Result<T> Ok<T>(T value) | |
{ | |
return new Result<T>(value, true, string.Empty); | |
} | |
} | |
public class Result<T> : Result | |
{ | |
private readonly T _value; | |
public T Value | |
{ | |
get | |
{ | |
if (!IsSuccess) | |
throw new InvalidOperationException(); | |
return _value; | |
} | |
} | |
protected internal Result(T value, bool isSuccess, string error) | |
: base(isSuccess, error) | |
{ | |
_value = value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment