Skip to content

Instantly share code, notes, and snippets.

@codehaks
Forked from xsoheilalizadeh/Result.cs
Created June 23, 2020 20:34
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 codehaks/c91d0e9eaa0a20dfa3e0dcd040ada30e to your computer and use it in GitHub Desktop.
Save codehaks/c91d0e9eaa0a20dfa3e0dcd040ada30e to your computer and use it in GitHub Desktop.
using System;
using static Domain.Result;
namespace Domain
{
public readonly struct Result
{
private readonly Result<int, StringError> _result => new Result<int, StringError>(0);
public int Value => _result.Value;
public StringError? Error => _result.Error;
public bool Succeeded => _result.Succeeded;
public static Result<TValue, StringError> Ok<TValue>(TValue value) => new Result<TValue, StringError>(value);
}
public readonly struct Result<TValue>
{
public Result(TValue value) : this()
{
_result = new Result<TValue, StringError>(value);
}
private readonly Result<TValue, StringError> _result;
public TValue Value => _result.Value;
public StringError? Error => _result.Error;
public bool Succeeded => _result.Succeeded;
public static Result<TValue, StringError> Ok(TValue value) => new Result<TValue, StringError>(value);
public static implicit operator Result<TValue>(Result<TValue, StringError> result) =>
new Result<TValue>(result.Value);
}
public readonly struct Result<TValue, TError> where TError : Error
{
public Result(TValue value, TError? error = null)
{
Value = value;
Error = error;
}
public TValue Value { get; }
public TError? Error { get; }
public bool Succeeded => !(Error is null);
public static Result<TValue, TError> Ok(TValue value) => new Result<TValue, TError>(value);
}
public class StringError : Error
{
public override void Throw()
{
throw new NotImplementedException();
}
}
public abstract class Error
{
public static readonly Error Default = new StringError();
public abstract void Throw();
}
public class Order
{
public int Id { get; set; }
public Order(int id)
{
Id = id;
}
public static Result<Order> New() => Ok(new Order(1));
}
class Program
{
public static void Main(string[] args)
{
var result = Order.New();
if (result.Succeeded)
{
Console.WriteLine("Success!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment