ResultExtensions Class

Extension methods for the result types Res and ResT.

Definition

Namespace: Orx.Fun.Result
Assembly: Orx.Fun.Result (in Orx.Fun.Result.dll) Version: 1.3.0+344c8bdd6f720ccfb2d8db7c61b76cf02be18f5f
C#
public static class ResultExtensions
Inheritance
Object    ResultExtensions

Methods

Err(String) Creates a result as the Err variant; with the given error information: errorMessage.
C#
static Res AddUser(User user)
{
    if (AlreadyExists(user))
        return Err($"user '{user.Id}' already exists.");
    if (HasAvailableCapacity(session))
        return Err("not enough capacity");
    else
    {
        // add user
        return Ok();
    }
}
Err(String, Exception) Creates a result as the Err variant; with the given error information: when, exception.
C#
static Res PutItem(Item item)
{
    try
    {
        PutItemToDatabase(item);
        return Ok();
    }
    catch (Exception e)
    {
        return Err(nameof(PutItem), e);
    }
}
Err(String, String) Creates a result as the Err variant; with the given error information: errorMessage, when.
Err(String, String, Exception) Creates a result as the Err variant; with the given error information: errorMessage, when, exception.
C#
static Res PutItem(Item item)
{
    try
    {
        PutItemToDatabase(item);
        return Ok();
    }
    catch (Exception e)
    {
        return Err("failed to execute sql command.", nameof(PutItem), e);
    }
}
ErrT(String) Creates a result of T as Err with the given errorMessage.
C#
static Res<double> Divide(double number, double divider)
{
    if (divider == 0)
        return Err<double>("Cannot divide to zero");
    else
        return Ok(number / divider);
}
ErrT(String, String) Creates a result of T as Err with the given errorMessage which is observed during when.
Flatten(ResRes) Flattens the result of result; i.e., Res<Res> -> Res, by mapping:
  • Err => Err,
  • Ok(Err) => Err,
  • Ok(Ok) => Ok.
C#
Res<Res> nestedResult = Err<Res>("msg");
Res result = nestedResult.Flatten();
Assert(result.IsErr and result.ErrorMessage() == Some("msg"));

Res<Res> nestedResult = Ok(Err("msg"));
Res result = nestedResult.Flatten();
Assert(result.IsErr and result.ErrorMessage() == Some("msg"));

Res<Res> nestedResult = Ok(Ok());
Res result = nestedResult.Flatten();
Assert(result.IsOk);
FlattenT(ResResT) Flattens the result of result of T; i.e., Res<Res<T>> -> Res<T>, by mapping:
  • Err => Err,
  • Ok(Err) => Err,
  • Ok(Ok(value)) => Ok(value).
C#
Res<Res<int>> nestedResult = Err<Res<int>>("msg");
Res<int> result = nestedResult.Flatten();
Assert(result.IsErr and result.ErrorMessage() == Some("msg"));

Res<Res<int>> nestedResult = Ok(Err<int>("msg"));
Res<int> result = nestedResult.Flatten();
Assert(result.IsErr and result.ErrorMessage() == Some("msg"));

Res<Res<int>> nestedResult = Ok(Ok(42));
Res<int> result = nestedResult.Flatten();
Assert(result.IsOk and result.Unwrap() == 42);
IntoResT(OptT) Shorthand for mapping options to results as follows:
  • None<T> => Err<T> with a generic error message;
  • Some(T) => Ok(T).
IntoResT(OptT, String) Shorthand for mapping options to results as follows:
  • None<T> => Err<T> with the given error message;
  • Some(T) => Ok(T).
MapT1, T2, TOut(ResValueTupleT1, T2, FuncT1, T2, TOut) Allows a result of a tuple (t1, t2) to map with a function taking two arguments t1 and t2.
C#
static int Add(int a, int b) => a + b;

var numbers = Ok((1, 2));
var sum = numbers.Map(Add);
Assert(sum == Some(3));
This is mostly useful in enabling function composition.
MapT1, T2, TOut(ResValueTupleT1, T2, FuncT1, T2, TaskTOut) (async version) Allows a result of a tuple (t1, t2) to map with a function taking two arguments t1 and t2.
C#
static int Add(int a, int b) => a + b;

var numbers = Ok((1, 2));
var sum = numbers.Map(Add);
Assert(sum == Some(3));
This is mostly useful in enabling function composition.
MapReduceT(IEnumerableT, FuncT, Res) Applies the result mapper to the collection and reduces it to a single result:
  • returns Ok when all results are Ok;
  • Ok if the collection is empty;
  • the first Err otherwise.
MapReduceT, TOut(IEnumerableT, FuncT, ResTOut) Applies the result mapper to the collection and reduces it to a single result:
  • returns Ok(List<T>) when all results are Ok;
  • Ok(empty list of T) if the collection is empty;
  • the first Err otherwise.
MapReduceAsyncT(IEnumerableT, FuncT, TaskRes) (async version) Applies the result mapper to the collection and reduces it to a single result:
  • returns Ok when all results are Ok;
  • Ok if the collection is empty;
  • the first Err otherwise.
MapReduceAsyncT, TOut(IEnumerableT, FuncT, TaskResTOut) (async version) Applies the result mapper to the collection and reduces it to a single result:
  • returns Ok(List<T>) when all results are Ok;
  • Ok(empty list of T) if the collection is empty;
  • the first Err otherwise.
Ok Creates a result as the Ok variant.
C#
Res result = Ok();
Assert(result.IsOk);
OkT(T) Creates a result of T as Ok variant with value value. However, if the value is null, it will map into Err.
C#
Res<double> number = Ok(42.5);
Assert(number.IsOk and number.Unwrap() == 42.5);

// on the other hand:
string name = null;
Res<string> optName = Ok(name);
Assert(optName.IsErr);
OkIf(Boolean, String) Creates a result as Ok variant if the okCondition holds. Otherwise, it will map into an Err.
C#
static Res ValidateInput(Form form)
{
    return OkIf(!form.HasEmptyFields())
        .OkIf(form.Date <= DateTime.Now)
        // chained validation calls
        .OkIf(repo.AlreadyContains(form.Id));
}
OkIfT(Boolean, T, String) Creates a result of T as Ok variant with value value if the okCondition holds. Otherwise, it will map into an Err.
C#
Shape shape = GetShape(); // valid only if shape has a positive base area.
Res<Shape> resultShape = OkIf(shape.GetBaseArea() > 0, shape);
OkIfT(Boolean, FuncT, String) Creates a result of T as Ok variant with value lazyGetValue() if the okCondition holds. Otherwise, it will map into an Err. Note that the lazyGetValue is only evaluated if the okCondition holds.
C#
Res<User> user = TryGetUser();
// create a database connection (expensive) only if the user IsOk.
Res<Conn> conn = OkIf(user.IsOk, () => CreateDatabaseConnection());
OkIfNotnullT Creates a result of T as Ok variant with the given value. However, if the value is null, it will map into Err.
C#
string name = null;
static string? GetName(int id)
    => id == 0 ? "Mr Crabs" : null;
Res<string> resName = GetName(0).OkIfNotnull();
Assert.Equal(Ok("Mr Crabs"), resName);

resName = GetName(42).OkIfNotnull();
Assert.True(resName.IsErr);
Reduce(IEnumerableRes) Reduces the collection of results to a single result:
  • returns Ok when all results are Ok;
  • Ok if the collection is empty;
  • the first Err otherwise.
ReduceT(IEnumerableResT) Reduces the collection of results to result of list of values:
  • returns Ok(List<T>) when all results are Ok;
  • Ok(empty list of T) if the collection is empty;
  • the first Err otherwise.
ReduceAsync(IEnumerableTaskRes) (async version) Reduces the collection of results to a single result:
  • returns Ok when all results are Ok;
  • Ok if the collection is empty;
  • the first Err otherwise.
ReduceAsyncT(IEnumerableTaskResT) (async version) Reduces the collection of results to result of list of values:
  • returns Ok(List<T>) when all results are Ok;
  • Ok(empty list of T) if the collection is empty;
  • the first Err otherwise.

See Also