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
TThe 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:
- Some(T?) to create a present value.
- None() to represent absence.
- OrDefault(T?) / OrThrow(string?) / Map<TOut>(Func<T?, TOut?>) for use.
It is immutable and does not box primitives.
Properties
HasValue
Indicates whether the option contains a value.
public bool HasValue { get; }
Property Value
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
fFunc<T, TOut>The mapping function applied when a value is present.
Returns
Type Parameters
TOutThe 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
fallbackTThe 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
messagestringAn 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
valueTThe value to wrap. May be null for reference types.
Returns
- Option<T>