OptionExtensions Class

Extension methods for the option type OptT.

Definition

Namespace: Orx.Fun.Option
Assembly: Orx.Fun.Option (in Orx.Fun.Option.dll) Version: 1.2.1+ea79806fa5e0e04bfdaef2a1916930e75e2cde74
C#
public static class OptionExtensions
Inheritance
Object    OptionExtensions

Methods

FlattenT Flattens the option of option of T. Maps Opt<Opt<T>> to Opt<T> as follows:
  • None => None<T>(),
  • Some(None<T>()) => None<T>(),
  • Some(Some(T)) => Some(T).
C#
Assert(None<Opt<char>>().Flatten() == None<char>());
Assert(Some(None<char>()).Flatten() == None<char>());
Assert(Some(Some('c')).Flatten() == Some('c'));
MapT1, T2, TOut(OptValueTupleT1, T2, FuncT1, T2, TOut) Allows an option 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 = Some((1, 2));
var sum = numbers.Map(Add);
Assert(sum == Some(3));
This is mostly useful in enabling function composition.
MapT1, T2, TOut(OptValueTupleT1, T2, FuncT1, T2, TaskTOut) (async version) Allows an option 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 = Some((1, 2));
var sum = numbers.Map(Add);
Assert(sum == Some(3));
This is mostly useful in enabling function composition.
NoneT Creates an option of T as None variant.
C#
var noneInt = None<int>();
Assert(noneInt.IsNone);

// also:
Opt<string> name = default;
Assert(name.IsNone);
SomeT Creates an option of T as Some variant with the given value. However, if the value is null, it will map into None.
C#
Opt<double> number = Some(42.5);
Assert(number.IsSome and number.Unwrap() == 42.5);

// on the other hand:
string name = null;
Opt<string> optName = Some(name);
Assert(optName.IsNone);
SomeIfT(Boolean, T) Creates a result of T as Some variant with value value if the someCondition holds. Otherwise, it will return the None variant.
C#
string team = "secret";
int score = 42;

Opt<string> winner = SomeIf(score > 30, team);
Assert(winner == Some(team));

Opt<string> loser = SomeIf(score < 40, team);
Assert(loser.IsNone);
SomeIfT(Boolean, FuncT) Lazy-in-evaluating-value counterpart of SomeIfT(Boolean, T).
SomeIfNotnullT Creates an option of T as Some variant with the given value. However, if the value is null, it will map into None.
C#
string name = null;
static string? GetName(int id)
    => id == 0 ? "Mr Crabs" : null;
Opt<string> optName = GetName(0).SomeIfNotnull();
Assert.Equal(Some("Mr Crabs"), optName);

optName = GetName(42).SomeIfNotnull();
Assert.True(optName.IsNone);

See Also