Optional
Optional<T>
Section titled “Optional<T>”Represents a value that is either Some, holding a T, or None.
Creating optionals
Section titled “Creating optionals”var some = Optional<string>.Some("hello");var none = Optional<string>.None();
// From a possibly-null valuevar maybe = Optional<string>.From(GetNickname()); // Some or None depending on null
// Or via the static Optional helpersvar some2 = Optional.Some("hello");var none2 = Optional.None<string>();var maybe2 = Optional.From(GetNickname());Implicit conversion
Section titled “Implicit conversion”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;Properties and access
Section titled “Properties and access”| Member | Type | Description |
|---|---|---|
IsSome | bool | true if the optional holds a value. |
Value | object | The value when Some, otherwise None. Prefer TryGetValue or Match. |
TryGetValue(out T value) | bool | Outputs the value and returns true when Some. |
TryGetValue(out None none) | bool | Outputs None and returns true when empty. |
Pattern matching
Section titled “Pattern matching”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 */ }Optional static helpers
Section titled “Optional static helpers”| Member | Description |
|---|---|
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. |
Equality
Section titled “Equality”Optional<T> implements IEquatable<Optional<T>> and supports == / !=. Two optionals are equal if they are both empty, or both hold equal values.
ToString
Section titled “ToString”Optional<T>.ToString() returns Some(value) when Some, or None when empty.