Package Description
$ dotnet add package Optional2![]()
Optional is a robust option/maybe type for C#. Originally developed by Nils Lück - Optional
Optional is a strongly typed alternative to null values that lets you:
where T : class and where T : struct are no longer neededPM> Install-Package Optional2
NuGet package. Supports .NET 3.5+ and .NET (.NET Standard 1.0+)
To use Optional simply import the following namespace:
using Optional;
A few auxiliary namespaces are provided:
using Optional.Linq; // Linq query syntax support
using Optional.Unsafe; // Unsafe value retrieval
using Optional.Collections; // Linq like methods with Option specifics
// The most basic way to create optional values is to use the static `Option` class:
var none = Option.None<int>();
var some = Option.Some(10);
// or use extension methods:
var none = 10.None(); // Equivalent to Option.None<int>()
var some = 10.Some();
Option can be filtered during creation by methods .Some*() or .None*(). The most useful from them is .SomeNotNull() since Nullable Reference Types are supported. Analogue for value types is .ToOption().
When retrieving values, Optional forces you to consider both cases (that is if a value is present or not).
Like Nullable<T> Option can be tested by HasValue property.
There are also more precise ways:
var isThousand = option.Contains(1000);
var isGreaterThanThousand = option.Exists(val => val > 1000);
Ways to retrieve a value from Option are:
var value = option.ValueOr(10); // Returns the value if Some, or otherwise an alternative value (10)
var value = option.Match(
some: x => x + 1,
none: () => 10
); // pattern matching
var value = option.ValueOrFailure(); // Unsafe: throws OptionValueMissingException on None
var value = 10.Some();
var doubled = value.Map(x => x * 2); // Some(20)
var odd = doubled.Filter(x => x % 2 == 1); // None
var fallback = odd.Else(1.Some()); // Some(1)
For details see Option<T> or explore xml doc.
using Optional.Linq;
var personWithGreenHair =
from person in FindPersonById(10)
from hairstyle in GetHairstyle(person)
where hairstyle.Color == "green"
select person;
An Option<T, TException> type with similar capabilities.
var none = Option.None<int, ErrorCode>(ErrorCode.GeneralError);
var some = Option.Some<int, ErrorCode>(10);
IEnumerable<T> related Linq similar methods (First|Last|Signle)OrNone()items.Values() keeps only Some from items and unwraps themdictionary.GetValueOrNone(key: 42) - lookups an entry by key