Table of Contents

Struct Option<T>

Namespace
PatternKit.Common
Assembly
PatternKit.Core.dll

A lightweight optional value type with no allocations, suitable for hot paths.

public readonly struct Option<T>

Type Parameters

T

The wrapped value type.

Inherited Members

Examples

var maybe = Option<int>.Some(5);
var value = maybe.OrDefault(); // 5
var mapped = maybe.Map(x => x * 2).OrDefault(); // 10

Remarks

Option<T> is a simple triad of operations:

It is immutable and does not box primitives.

Properties

HasValue

Indicates whether the option contains a value.

public bool HasValue { get; }

Property Value

bool

ValueOrDefault

Returns the contained value when present; otherwise default.

public T? ValueOrDefault { get; }

Property Value

T

Methods

Map<TOut>(Func<T?, TOut?>)

Maps the contained value to a new Option<T> using f.

public Option<TOut> Map<TOut>(Func<T?, TOut?> f)

Parameters

f Func<T, TOut>

The mapping function applied when a value is present.

Returns

Option<TOut>

Some(T?) containing the mapped value, or None() when empty.

Type Parameters

TOut

The result value type.

None()

Creates an empty Option<T>.

public static Option<T> None()

Returns

Option<T>

OrDefault(T?)

Returns the contained value when present; otherwise returns fallback.

public T? OrDefault(T? fallback = default)

Parameters

fallback T

The fallback value to return when the option is empty.

Returns

T

OrThrow(string?)

Returns the contained value when present; otherwise throws InvalidOperationException.

public T OrThrow(string? message = null)

Parameters

message string

An optional error message for the thrown exception.

Returns

T

Exceptions

InvalidOperationException

Thrown when the option is empty.

Some(T?)

Creates an Option<T> that contains a value.

public static Option<T> Some(T? value)

Parameters

value T

The value to wrap. May be null for reference types.

Returns

Option<T>