Skip to content

Instantly share code, notes, and snippets.

@1saeedsalehi
Last active March 18, 2020 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1saeedsalehi/af1d65e9668220f44e80c6c28b9e3019 to your computer and use it in GitHub Desktop.
Save 1saeedsalehi/af1d65e9668220f44e80c6c28b9e3019 to your computer and use it in GitHub Desktop.
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