Created
December 29, 2015 03:16
-
-
Save richardtallent/c5e1fb8a510c5f4d38b0 to your computer and use it in GitHub Desktop.
Special-purpose tuple for returning both a value and status from a function in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace RT { | |
/// <summary> | |
/// Generic, yet more expressive mechanism for returning both a value and a status from a function. | |
/// Nothing earth-shattering, just syntactic sugar and logic to create an immutable struct with | |
/// minimal effort. | |
/// | |
/// Usage: | |
/// return Result<foo>.Succeeded(myFoo); // returned foo is good | |
/// return Result<foo>.Failed(); // unsuccessful, no foo to return | |
/// return Result<foo>.Failed(badFoo); // unsuccessful, but there is a foo to return | |
/// | |
/// Static members on generic types are usually discouraged because they require specifying the type | |
/// when called, but these are simply replacing the need for a constructor, which does the same. | |
/// </summary> | |
public struct Result<T> { | |
public T Value { get; private set; } | |
public bool Success { get; private set; } | |
public static Result<T> Succeeded(T returnValue) { | |
return new Result<T> { Value = returnValue, Success = true }; | |
} | |
public static Result<T> Failed(T returnValue = default(T)) { | |
return new Result<T> { Value = returnValue } ; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment