Skip to content

Instantly share code, notes, and snippets.

@costr
Created July 20, 2023 13:43
Show Gist options
  • Save costr/8a2dc474f948f9880ec297e692abc844 to your computer and use it in GitHub Desktop.
Save costr/8a2dc474f948f9880ec297e692abc844 to your computer and use it in GitHub Desktop.
Result Pattern Class
public class Result<T>
{
private readonly T _value;
public T Value { get { return _value; } }
private List<string> _errors = new List<string>();
public IReadOnlyCollection<string> Errors => _errors;
private List<Exception> _exceptions = new List<Exception>();
public IReadOnlyCollection<Exception> Exceptions => _exceptions;
public bool IsSuccess => _errors == null || !_errors.Any();
public bool HasException => _exceptions != null && _exceptions.Any();
private Result(T value, List<string> errors = null)
{
_value = value;
_errors = errors ?? _errors; // if default param, for errors, is used then just keep the empty collection instead of nulling it
}
public static Result<T> Success(T value)
{
return new Result<T>(value);
}
public static Result<T> Failure(List<string> errors)
{
if (errors == null || errors.Count == 0)
{
throw new ArgumentException("Errors list must not be null or empty.", nameof(errors));
}
return new Result<T>(default, errors);
}
public static Result<T> Failure(string error)
{
if (string.IsNullOrWhiteSpace(error))
{
throw new ArgumentException("Error message must not be null or empty.", nameof(error));
}
return new Result<T>(default, new List<string> { error });
}
public static Result<T> Failure(string errorMessage, Exception exception)
{
if (string.IsNullOrWhiteSpace(errorMessage))
{
throw new ArgumentException("Error message must not be null or empty", nameof(errorMessage));
}
if (exception == null)
{
throw new ArgumentException("Exception may not be null", nameof(exception));
}
var result = new Result<T>(default);
result.AddFailureWithException(errorMessage, exception);
return result;
}
public void AddFailure(string error)
{
if (string.IsNullOrWhiteSpace(error))
{
throw new ArgumentException("Error message must not be null or empty", nameof(error));
}
_errors.Add(error);
}
public void AddFailureWithException(string errorMessage, Exception exception)
{
if (string.IsNullOrWhiteSpace(errorMessage))
{
throw new ArgumentException("Error message must not be null or empty", nameof(errorMessage));
}
if (exception == null)
{
throw new ArgumentException("Exception may not be null", nameof(exception));
}
_errors.Add(errorMessage);
_exceptions.Add(exception);
}
public override string ToString()
{
return IsSuccess ? "The result is successful" : $"The following error{(_errors.Count > 1 ? "s" : "")} encountered: {Environment.NewLine}-{string.Join($"{Environment.NewLine}-", _errors)}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment