Skip to content

Creates a simple struct that can be used as discriminated union return type

License

Notifications You must be signed in to change notification settings

mroberts91/Either

Repository files navigation

Either

Nuget GitHub GitHub last commit (branch)

Creates a simple struct that can be used as a discriminated union like return type, supporting the successful result as well as up to four additonal exceptions that can be returned.

Available Variations

public struct Either<T, TError> {}
public struct Either<T, TError1, TError2> {}
public struct Either<T, TError1, TError2, TError3> {}
public struct Either<T, TError1, TError2, TError3, TError4> {}

Example using the built in Resolve method

public IActionResult Get(Guid id) => 
   _repository.User(id).Resolve<IActionResult>(
      user => Ok(user),
      error => NotFound()
   );

Example using C# pattern mathcing

public IActionResult Post([FromBody] UserCreateRequest request)
{
    var result = _repository.Create(request.Email, request.Name);
            
    return result.Value switch
    {
        Guid guid =>  Created(guid.ToString(), guid),
        ArgumentException ex => BadRequest(new { ex.Message, request }),
        InvalidDataContractException ex => BadRequest(new { ex.Message, request }),
        _ => ServerError()
    };
}

About

Creates a simple struct that can be used as discriminated union return type

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages