Skip to content

Optional

Represents a value that is either Some, holding a T, or None.

var some = Optional<string>.Some("hello");
var none = Optional<string>.None();
// From a possibly-null value
var maybe = Optional<string>.From(GetNickname()); // Some or None depending on null
// Or via the static Optional helpers
var some2 = Optional.Some("hello");
var none2 = Optional.None<string>();
var maybe2 = Optional.From(GetNickname());

A value converts implicitly to an Optional<T>, null becoming None; the None marker struct also converts implicitly:

Optional<string> Nickname(User user) => user.Nickname; // null becomes None
Optional<string> Empty() => None.Default;
MemberTypeDescription
IsSomebooltrue if the optional holds a value.
ValueobjectThe value when Some, otherwise None. Prefer TryGetValue or Match.
TryGetValue(out T value)boolOutputs the value and returns true when Some.
TryGetValue(out None none)boolOutputs None and returns true when empty.

Optional<T> is marked [Union] and implements IUnion, so C# pattern matching recognizes Some and None as its cases — a switch expression works alongside Match:

string label = optional.Match(
onSome: value => $"Got {value}",
onNone: () => "none");
string label2 = optional switch
{
int value => $"Got {value}",
None => "none",
};

A switch covering T and None is exhaustive for any T, reference or value type — no discard arm is needed, and the compiler warns (CS8509) if either is missing. A default Optional<T> (e.g. default(Optional<T>)) matches None.

is patterns work too:

if (optional is int value) { /* Some, holding value */ }
if (optional is None) { /* None */ }

MemberDescription
Optional.Some<T>(value)Creates an optional holding value. Throws ArgumentNullException if value is null.
Optional.From<T>(value)Creates an optional from a nullable reference or nullable value type; null becomes None.
Optional.None<T>()Creates an empty optional.

Optional<T> implements IEquatable<Optional<T>> and supports == / !=. Two optionals are equal if they are both empty, or both hold equal values.

Optional<T>.ToString() returns Some(value) when Some, or None when empty.