Creation
The factory methods that build an Option<T>.
Option.Some
Option<T> Option.Some<T>(T value)Wraps a value. The result is always Some.
Option<string> some = Option.Some("Hello Bees!");On null: throws ArgumentNullException. T is constrained notnull, and the constructor enforces it. A default value is fine — Option.Some(0) is a Some holding zero.
Option.None
Option<T> Option.None<T>()The empty case. You supply the type parameter because there is no value to infer it from.
Option<string> none = Option.None<string>();Option.FromNullable
Option<T> Option.FromNullable<T>(T? value)Some when the value is not null, None when it is. Use it at the edge of your code, where the shape is not yours to choose.
Option.Try
Option<T> Option.Try<T>(Func<T> factory)Runs a factory that might throw, and asks one question: did it hand back a value you can work with?
On a throw: the exception is caught, sent to your configured exception logger, and you get None.
On null: you get None, because a Some cannot hold one. Nothing is logged, because nothing threw. Option.Try(() => 0) gives you Some(0) — only null is rejected.
A cancellation is not caught. Try and TryAsync let an OperationCanceledException propagate, so a cancelled operation throws rather than becoming a None. Cancelling is you asking the work to stop, not the work failing. See Configuration to get the pre-6.0.0 behaviour back.
Do not pass an async factory to Try. It compiles, gives you an Option<Task<T>>, and catches nothing. Use TryAsync. WM1011 reports every occurrence.
Option.TryAsync
The same, for a factory that returns a Task. See Async.
Passing state to the factory
Try and TryAsync each take an optional first argument that they hand to your factory. Use it to keep the factory from capturing:
See State overloads for why this matters.
Last updated
Was this helpful?