API Browser

Union

Optional<T>

union struct Optional<T>

Namespace: System
Assembly: Raven.Core.dll
Source file: Optional.rvn

Inheritance: Object → ValueType → Optional<T>
Implements: IPropagatable<Optional<T>, T, Unit>

Represents an available value (Some) or meaningful absence (None). Use Optional<T> when having no value is an ordinary outcome. Use Result<T, E> when the caller needs a reason for failure.

Usage

Handle cases with if ... else

A profile form can leave its nickname field blank. This function trims the input and makes that absence explicit instead of using an empty string as a special value. The if ... else expression produces the optional value.

import System.*
import System.Optional.*

func ReadNickname(input: string) -> Optional<string> {
    let name = input.Trim()
    return if name.Length == 0 {
        None
    } else {
        Some(name)
    }
}

let nickname = ReadNickname(" Ada ")
if nickname is Some(let displayName) {
    Console.WriteLine("Welcome, ${displayName}!")
} else {
    Console.WriteLine("Welcome, guest!")
}
// Welcome, Ada!

Some(let displayName) both checks the case and binds its value. displayName is available only in the successful branch; the else branch handles None.

Extract a value or use a fallback with if let

Continuing the profile example, a heading needs a string in both cases. An if let expression binds the nickname when present and supplies a fallback when absent. Both branches compute the heading rather than performing an action.

let heading = if let Some(profileName) = ReadNickname("   ") {
    "Profile: ${profileName}"
} else {
    "Guest profile"
}
Console.WriteLine(heading)
// Guest profile

Propagate None with ?

A profile handle can be created only when a nickname exists. Here ? extracts the string from Some, or immediately returns None from CreateHandle. The remaining code runs only when there is a name. Wrap the final value in Some to return a successful optional result.

func CreateHandle(input: string) -> Optional<string> {
    let name = ReadNickname(input)?
    Some("@${name.ToLowerInvariant()}")
}

let handle = CreateHandle(" Ada ") // Some("@ada")
let missing = CreateHandle("   ") // None
Console.WriteLine(handle.UnwrapOr("guest"))
Console.WriteLine(missing.UnwrapOr("guest"))
// @ada
// guest

Choose an explicit branch when this function should provide a fallback or take a different action. Use ? when absence should remain absence for its caller. A match expression is also available when you want to handle both cases exhaustively.

Type parameters

Name Description
T The type of the optional value.

Cases

2 cases

Properties

4 items
HasNone: bool Gets a value indicating whether this option is `None`.
HasSome: bool Gets a value indicating whether this option is `Some`.
HasValue: bool Represents an available value (`Some`) or meaningful absence (`None`). Use `Optional<T>` when having no value is an ordinary outcome. Use [Result<T, E>](xref:T:System.Result`2) whe…
Value: object? Represents an available value (`Some`) or meaningful absence (`None`). Use `Optional<T>` when having no value is an ordinary outcome. Use [Result<T, E>](xref:T:System.Result`2) whe…

Methods

26 items
Equals(obj: object?) -> bool Indicates whether this instance and a specified object are equal. Inherited from ValueType.Equals
Extension member: Flatten() -> Optional<T> Flattens `Optional<Optional<T>>` into `Optional<T>`. Extension from OptionalExtensionsNested<T>.FlattenApplies to Optional<Optional<T>>.
Static member: FromResidual(residual: ()) -> Optional<T> Constructs an empty option from a propagated residual. Implements IPropagatable<Optional<T>, T, Unit>.FromResidual
GetEnumerator() -> IEnumerator<T> Returns an enumerator over the zero-or-one contained values.
GetHashCode() -> int Returns the hash code for this instance. Inherited from ValueType.GetHashCode
GetType() -> Type Gets the System.Type of the current instance. Inherited from Object.GetType
Map<TResult>(mapper: T -> TResult) -> Optional<TResult> Projects the value inside `Some` using `mapper`. `None` stays `None`.
MapResult<TResult, E>(mapper: T -> TResult, noneError: () -> E) -> Result<TResult, E> Maps the contained value into a `Result`. If this is `None`, returns `Failure(noneError())`.
Match<TResult>(some: T -> TResult, none: () -> TResult) -> TResult Matches the option and produces a value.
OkOr<E>(error: E) -> Result<T, E> Converts this option into a result, using `error` when it is `None`.
OkOr<E>(errorFactory: () -> E) -> Result<T, E> Converts this option into a result, evaluating `errorFactory` when it is `None`.
OrElse(alternative: () -> Optional<T>) -> Optional<T> Returns this option if it is `Some`, otherwise returns `alternative()`.
Tap(action: T -> ()) -> Optional<T> Runs `action` if this is `Some`, returning the original option.
TapNone(action: () -> ()) -> Optional<T> Runs `action` if this is `None`, returning the original option.
Then<TResult>(binder: T -> Optional<TResult>) -> Optional<TResult> Monadic bind / flatMap: chains an `Optional`-producing function.
ThenResult<TResult, E>(binder: T -> Result<TResult, E>, noneError: () -> E) -> Result<TResult, E> Bridges `Optional` into a `Result`-producing pipeline. If this is `None`, returns `Failure(noneError())`.
ToEnumerable() -> IEnumerable<T> Converts `Some(x)` to a single-item sequence and `None` to an empty sequence.
ToString() -> string No summary available. Overrides ValueType.ToString
TryGetOutput(output: out T) -> bool Attempts to extract the successful output used by the propagation protocol. Implements IPropagatable<Optional<T>, T, Unit>.TryGetOutput
TryGetResidual(residual: out ()) -> bool Reports absence as the unit residual used by the propagation protocol. Implements IPropagatable<Optional<T>, T, Unit>.TryGetResidual
UnwrapOr(defaultValue: T) -> T Returns the contained value, or `defaultValue` when this option is `None`.
UnwrapOrDefault() -> T Returns the contained value, or the default value when this option is `None`.
UnwrapOrElse(factory: () -> T) -> T Returns the contained value or evaluates `factory()`.
UnwrapOrThrow() -> T Returns the contained value, or throws when this option is `None`.
Where(predicate: T -> bool) -> Optional<T> Keeps the value only if `predicate` returns true.

Operators

2 items
Static extension member: implicit conversion(opt: Optional<T>) -> T? Converts an option to its nullable reference representation. Extension from OptionalExtensions1<T>.op_ImplicitApplies to Optional<T> where T: class.
Static extension member: implicit conversion(opt: Optional<T>) -> T? Converts an option to its nullable value representation. Extension from OptionalExtensions2<T>.op_ImplicitApplies to Optional<T> where T: struct.