Skip to content

Instantly share code, notes, and snippets.

@1saeedsalehi
Last active April 10, 2020 18:23
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/e7e490f04b1ea3084388d2aac6f2f466 to your computer and use it in GitHub Desktop.
Save 1saeedsalehi/e7e490f04b1ea3084388d2aac6f2f466 to your computer and use it in GitHub Desktop.
implementing Result in dotnet
using System;
namespace Excecptions
{
// Still a draft
class Program
{
static void Main(string[] args)
{
Action action = GetThing() switch
{
Ok<Thing> ok => () =>
{
// do stuff on success
Console.WriteLine(ok.Value);
},
Error<Thing> err => () =>
{
// do stuff on failure
Console.WriteLine(err.ErrorCode);
},
_ => throw new InvalidOperationException()
};
// then call your action
action();
// you simply want to get a string message of what happened
var resultMessage = DoIt() switch
{
Ok ok => "thing is done",
Error err => $"error occured | message: {err.ErrorMessage}",
_ => throw new InvalidOperationException()
};
Console.WriteLine(resultMessage);
}
static Result<Thing> GetThing()
{
return Result.Ok<Thing>(new Thing("foo_name"));
return Result.Error<Thing>("it is an err message");
}
static Result DoIt()
{
return Result.Error("it is an err message", 2);
return Result.Ok();
}
}
class Thing
{
public Thing(string name)
{
Name = name;
}
public string Name { get; }
}
class Result
{
public bool IsOk() => this is Ok;
public bool IsError() => this is Error;
public static Ok Ok() => new Ok();
public static Error Error(string message, int code) => new Error(message, code);
public static Error Error(string message) => new Error(message);
public static Ok<T> Ok<T>(T value) => new Ok<T>(value);
public static Error<T> Error<T>(string message, int code) => new Error<T>(message, code);
public static Error<T> Error<T>(string message) => new Error<T>(message);
}
class Ok : Result
{
}
class Result<T>
{
public bool IsOk() => this is Ok<T>;
public bool IsError() => this is Error<T>;
}
class Ok<T> : Result<T>
{
public T Value { get; }
public Ok(T value)
{
Value = value;
}
}
class Error : Result
{
public string ErrorMessage { get; }
public int ErrorCode { get; }
public Error(string errorMessage, int errorCode)
{
ErrorMessage = errorMessage;
ErrorCode = errorCode;
}
public Error(string errorMessage)
: this (errorMessage, -1)
{
}
}
class Error<T> : Result<T>
{
public string ErrorMessage { get; }
public int ErrorCode { get; }
public Error(string errorMessage, int errorCode)
{
ErrorMessage = errorMessage;
ErrorCode = errorCode;
}
public Error(string errorMessage)
: this(errorMessage, -1)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment