CSharpEssentials.Maybe
Maybe<T> makes a missing value explicit instead of null.
Installation
dotnet add package CSharpEssentials.Maybe
Namespace
using CSharpEssentials.Maybe;
Creating a Maybe
Maybe<string> name = user?.Name; // implicit T? → Maybe<T>: null → None, value → Some
Maybe<string> none = Maybe.None; // implicit Maybe → Maybe<T>
Maybe<string> some = "Alice";
var viaFrom = Maybe.From(user?.Name); // explicit factory where the type is not known (var, chains)
Maybe<User> viaExt = user.AsMaybe(); // extension on T?
Implicit conversion is the idiomatic style; Maybe.From(x) gives None when x is null (a bare null literal does not compile, because T cannot be inferred) and Some(x) otherwise. .AsMaybe() does the same on any T? (and on Result<T>); there is no .ToMaybe().
Checking the value
bool has = maybe.HasValue;
bool empty = maybe.HasNoValue;
string val = maybe.GetValueOrDefault("fallback");
string val2 = maybe.GetValueOrThrow(); // throws InvalidOperationException if None
bool ok = maybe.TryGetValue(out string? inner);
var (hasValue, value) = maybe; // Deconstruct
Exception-safe creation
// None if the factory throws; OperationCanceledException is rethrown
Maybe<int> n = Maybe<int>.FromTry(() => int.Parse(input));
Maybe<User> u = Maybe<User>.FromTry(() => JsonSerializer.Deserialize<User>(json)!);
Choosing between `T?`, `Maybe<T>` and `Result<T>`
T?at boundaries: DTOs, entity columns, JSON.Maybe<T>inside the domain, when absence is an expected state composed withMap/Bind.Result<T>when the failure carries a reason the caller acts on.- Exceptions only for bugs and invariant violations.
Maybe<string> middleName = entity.MiddleName; // boundary T? → domain Maybe<T>, implicit
Result<User> found = _cache.TryFind(id).ToMaybeResult(Error.NotFound("User.NotFound", "User does not exist"));
Equality: Maybe<int>.None == 0 is false, Maybe<int>.From(0) == 0 is true. A typed null compares as absence (Maybe<string>.None == null is true), in either operand order, but Equals(object?) and maybe == (object?)null follow the BCL rule and return false for null. Maybe<int> == null hits CS9342 and maybe == default means default(T) for value types, so use HasNoValue. ToString() returns Some(value) or None (invariant culture for IFormattable values). Use HasNoValue, not the obsolete IsNone.
Pattern matching
string result = maybe.Match(
some: name => $"Hello, {name}",
none: () => "Hello, stranger");
Transforming
// Map: transform the inner value if present
string display = Maybe.From(user?.Email)
.Map(e => e.ToLowerInvariant())
.GetValueOrDefault("no email");
// Bind (flatMap): when the transform itself returns Maybe<T>
Maybe<Address> address = Maybe.From(user)
.Bind(u => Maybe.From(u.Address));
// Flatten: Maybe<Maybe<T>> → Maybe<T>, and Maybe<T>? → Maybe<T> (null becomes None)
Maybe<int> points = customer.LoyaltyPoints.Flatten(); // Maybe<int>? from an EF nullable column
Side effects on None
// TapNone: runs only when None; returns the same Maybe unchanged
maybe.TapNone(() => logger.LogWarning("Value was absent"));
// Async: instance and extension variants
await maybe.TapNoneAsync(async () => await NotifyAsync());
await GetMaybeAsync().TapNoneAsync(() => fallback());
// GetValueOrElse: factory called only on None
int v = maybe.GetValueOrElse(() => ComputeExpensiveDefault());
// OrElse: lazy Maybe chain, alias for Or(Func<Maybe<T>>)
Maybe<Config> cfg = GetCached().OrElse(() => LoadFromDisk());
await GetCached().OrElseAsync(() => Task.FromResult(LoadFromDisk()));
Bridge to Result
// Convert Maybe → Result, providing the error for the None case
Result<string> r = maybe.ToMaybeResult(
Error.NotFound("user.email", "No email address on file."));
// Result<T> → Maybe<T> (a failure becomes None and its errors are dropped)
Maybe<string> back = r.AsMaybe();
ToResult(error) is an alias of ToMaybeResult(error). Always pass the error to ToResult: maybe.ToResult() with no argument binds the generic ToResult<TValue>(this TValue value) of CSharpEssentials.Results and returns a successful Result<Maybe<T>>. ToMaybeResult() without an error is fine and uses the Maybe.Result NotFound error.
Filtering, fallbacks and sequences
Maybe<int> big = maybe.Where(v => v > 3); // None when the predicate fails
Maybe<int> alt = none.Or(7); // Or(Maybe<T>), Or(Func<T>), Or(Func<Maybe<T>>)
maybe.Tap(v => logger.LogInformation("{V}", v)); // only on Some; TapIf adds a condition
maybe.Execute(v => Save(v)); // Action<T> on Some; ExecuteNoValue(Action) on None
Maybe<int> kept = maybe.MapIf(v => v > 3, v => v * 2); // BindIf works the same with a Maybe-returning function
Maybe<User[]> all = ids.Traverse(id => FindUser(id)); // None if any lookup is None
Maybe<int[]> seq = maybes.Sequence(); // None if any element is None
var (values, noneCount) = maybes.Partition();
IEnumerable<int> present = maybes.Choose(); // keep the present values
Maybe<User> first = users.TryFirst(u => u.IsActive); // TryLast, and dictionary.TryFind(key)
TryFirst and TryLast return None for an empty sequence or a predicate without a match, value types included, and a null element gives None.
Async naming
Every Maybe member that returns Task or ValueTask ends in Async: WhereAsync, ExecuteAsync, ExecuteNoValueAsync, OrAsync, MatchAsync, ToMaybeResultAsync, ToMaybeUnitResultAsync and Maybe.FromAsync. The old unsuffixed overloads are [Obsolete] forwarders; never write them. OrElseAsync keeps its name. An untyped async lambda on an instance ExecuteAsync, ExecuteNoValueAsync, OrAsync, WhereAsync or MatchAsync, or on a key/value MatchAsync, binds the Task overload only on C# 13 or later; on C# 12, type the lambda (Func<T, Task>). maybe.MapAsync(async v => ...) is ambiguous (CS0121) on every language version: pass a lambda that returns a Task or type the delegate.
Rules
- Prefer implicit conversion (
Maybe<T> m = value;,return value;,Maybe.None); useMaybe.From()or.AsMaybe()where the target type is not known. - Prefer
Match()overHasValueplusGetValueOrThrow(). - Use
Bind()when the transform returnsMaybe<T>. - Bridge to
ResultwithToMaybeResult(error)when the caller needs a reason.