Option¶
Option<T> is a value that may be missing, where missing is normal and not an error. It holds a T or None. It is a struct, so there is no null option.
In this section¶
- Core concepts: what an option is, how to create one, its members, and how to match it.
- Operations:
Select,Chain,Where,Zip,Or,Matchand the other operators. - Collections:
FirstOrNone,GetValueOrNone,Values,Combineand friends. - Conversions: between options, nullable types and results.
- Patterns: replacing
nullreturns, fallbacks, optional configuration and DTO fields.
Quick example¶
using Fluent.Unions;
static Option<Customer> FindCustomer(Guid id) =>
customers.GetValueOrNone(id);
string label = FindCustomer(id)
.Select(customer => customer.Name)
.GetValueOrDefault("guest"); // "Ada", or "guest" when the customer does not exist
When to use¶
- A lookup that finds nothing is a normal outcome: a cache miss, a customer without a nickname, an empty cart.
- You want the caller to handle the missing case, and you do not want to rely on
nullchecks. - Use a
Result<T>instead when the failure has a reason the caller should see. See patterns.
Rules¶
- Write
None or nullor_in aswitch, not onlyNone. Adefaultoption holds neither case. See core concepts. 0,falseand""are values. OnlynullandNonemean no value.- Option operators never catch exceptions. An exception thrown in a lambda, or a faulted task, propagates. The one exception is the error factory of
ToResult, which produces a result, so its exception becomes the error. SingleOrNonethrows when there are several elements, asSingleOrDefaultdoes.Option.Some(null)throwsArgumentNullException. UseToOption()when the value may benull.
Back to index: Docs index ยท Next: Core concepts