Skip to content

Instantly share code, notes, and snippets.

@habib-sadullaev
Last active October 13, 2023 11:23
Show Gist options
  • Save habib-sadullaev/d8ddc195401a4e11f41eee85b5647205 to your computer and use it in GitHub Desktop.
Save habib-sadullaev/d8ddc195401a4e11f41eee85b5647205 to your computer and use it in GitHub Desktop.
using System.Diagnostics.CodeAnalysis;
using System;
static Result<Foo, Err> GetResult(bool isErr)
=> isErr ? Result.Ok(new Foo()) : Result.Error(new Err());
Console.WriteLine(GetResult(true) switch
{
{ Success: true, Value: var value } => value,
{ Success: false, Error: var error } => error,
});
public class Foo {}
public class Err {}
public static class Result
{
public static OkResult<TValue> Ok<TValue>(TValue okValue) => new(okValue);
public static ErrorResult<TError> Error<TError>(TError errorValue) => new(errorValue);
}
public sealed class OkResult<TValue>
{
internal OkResult(TValue value) => Value = value;
public TValue Value { get; }
}
public sealed class ErrorResult<TError>
{
internal ErrorResult(TError error) => Error = error;
public TError Error { get; }
}
public sealed class Result<TValue, TError> where TValue : notnull where TError : notnull
{
Result(TValue? value, TError? error) => (Value, Error) = (value, error);
public TValue? Value { get; }
public TError? Error { get; }
[MemberNotNullWhen(true, nameof(Value))]
[MemberNotNullWhen(false, nameof(Error))]
public bool Success => this is { Value: not null, Error: null };
public static implicit operator Result<TValue, TError>(OkResult<TValue> result) => CreateValue(result.Value);
public static implicit operator Result<TValue, TError>(ErrorResult<TError> result) => CreateError(result.Error);
static Result<TValue, TError> CreateValue(TValue value) => new(value, default);
static Result<TValue, TError> CreateError(TError error) => new(default, error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment