Skip to content

About

A simple yet powerful implementation of the Result pattern for .NET, allowing returning a Result instead of throwing an exception for non-exceptional failures.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

Result.Simplified

License
Build Status codecov
NuGet version NuGet downloads
.NET 8.0 .NET Standard 2.0

Version 3.0 breaking changes

  • Removed the obsolete Result (non-generic) type
  • VoidResult and Result<T> are no longer related by inheritance
  • Added Map and Bind to Result<T> for functional composition

Result.Simplified enables .NET methods to return an explicit indication of success or failure for any return type (including void).
It is not intended to replace exceptions, but rather to represent non-exceptional failure cases as part of normal control flow.

Both VoidResult and Result<T> have built-in factory methods to simplify consuming code, such as SuccessIf, FailIf and Try. The Result<T> also implements Map and Bind enabling monadic operations.

Use VoidResult to enable void methods to return an indication of success or failure, and Result<T> to enable non-void methods to do the same.

Both VoidResult and Result<T> overload the & and | operators as well as the true and false operators, meaning you can easily combine results in a short-circuit manner for easy validations.

Usage example:

Return a VoidResult from a method:

VoidResult DoSomething()
{
    // some code...
    return condition
        ? VoidResult.Success()
        : VoidResult.Fail("Something went wrong...");
}

or

VoidResult DoSomething()
{
    // some code...
    return VoidResult.SuccessIf(condition, "Something went wrong...");
}

or

VoidResult DoSomething()
{
    // some code...
    return VoidResult.FailIf(negativeCondition, "Something went wrong...");
}

Return a Result<T> from a method:

Result<int> DoSomethingAndReturnAnInt()
{
    // some code...
    return condition
        ? Result<int>.Success(5)
        : Result<int>.Fail("Something went wrong...");
}

or

Result<int> DoSomethingAndReturnAnInt()
{
    // some code...
    return Result<int>.SuccessIf(condition, 5, "Something went wrong...", false);
    // The boolean at the end determines whether to include the value in the failed result.
}

or

Result<int> DoSomethingAndReturnAnInt()
{
    // some code...
    return Result<int>.FailIf(negativeCondition, 5, "Something went wrong...", true);
    // The boolean at the end determines whether to include the value in the failed result.
}

Consume a method that returns a VoidResult

void DoIfMethodSucceeded()
{
    var result = DoSomething();
    if(!result.IsSuccess)
    {   
        // Something went wrong, do something with result.ErrorDescription 
        // log or show the user or whatever
        return;
    }
    // Everything is fine, you can go on with your code
}

Consume a method that returns a Result<T>

bool DoIfMethodSucceeded()
{
    var result = DoSomethingAndReturnAnInt();
    if(!result.IsSuccess)
    {   
        // Something went wrong, do something with result.ErrorDescription 
        // Log or show the user or whatever
        return false;
    }
    var intValue = result.Value;
    // Everything is fine, you can go on with your code
}

Note: Since VoidResult and Result<T> overloads the true and false operators, you don't technically have to use the IsSuccess property to check if the result is a success or not, but I do recommend it for readability.

void DoIfMethodSucceeded()
{
    var result = DoSomething();
    if(!result)
    {   
        // Something went wrong, do something with result.ErrorDescription 
        // log or show the user or whatever
        return;
    }
    // Everything is fine, you can go on with your code
}

Since VoidResult and Result<T> also overload the & and | operators, you can combine multiple results in a short-circuit manner.

Result FailFast()
{
    var result = DoSomething() // returns a result instance
        && DoSomethingElse() // returns another result instance
        && DoAnotherThing() // returns another result instance;

    // result is the first failed result, or the last one if all succeeded.

    return result;
}

Result SuccessIfAny()
{

    var result = DoSomething() // returns a result instance
        || DoSomethingElse() // returns another result instance
        || DoAnotherThing() // returns another result instance;
    
    // result is the first successful result, or the last one if all failed.

    return result;    
}

You can chain result objects for validation:

Result<SomeObject> Validate(SomeObject someObject)
{
    
    return Validate("someObject is null.", d => d is object) 
        && Validate("someObject has no SomeProperty.", d => d.SomeProperty is object) 
        && Validate("SomeProperty is invalid.", d => d.SomeProperty.IsValid) 
        && Validate("SomeCollection is empty.", d => (d.SomeCollection?.Count ?? 0) > 0);

    Result<SomeObject> Validate(string errorMessage, Predicate<SomeObject> predicate)
    {
        var isValid = predicate(someObject);
        if (!isValid)
        {
            // Optionally log non-exceptional error here...
        }
        return isValid 
            ? Result<SomeObject>.Success(someObject) 
            : Result<SomeObject>.Fail(errorMessage);
    }
}

Functional composition with Map and Bind

Result<T> supports functional composition via Map and Bind.

Use Map when transforming a successful value:

Result<int> Parse(string input)
{
    return int.TryParse(input, out var value)
        ? Result<int>.Success(value)
        : Result<int>.Fail("Invalid number");
}

Result<string> result =
    Parse("42")
        .Map(x => x * 2)
        .Map(x => $"Value is {x}");

Use Bind when the transformation itself returns a Result<T>:

Result<int> ValidatePositive(int value)
{
    return value > 0
        ? Result<int>.Success(value)
        : Result<int>.Fail("Value must be positive");
}

Result<int> result =
    Parse("42")
        .Bind(ValidatePositive)
        .Bind(v => Result<int>.Success(v * 10));

About

A simple yet powerful implementation of the Result pattern for .NET, allowing returning a Result instead of throwing an exception for non-exceptional failures.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages