- Notifications
You must be signed in to change notification settings - Fork75
A robust option type for C#
License
nlkl/Optional
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Optional is a robust option/maybe type for C#.
Version: 4.0.0
Optional is a strongly typed alternative to null values that lets you:
- Avoid those pesky null-reference exceptions
- Signal intent and model your data more explictly
- Cut down on manual null checks and focus on your domain
- Robust and well tested
- Self contained with no dependencies
- Easily installed through NuGet
- Supports.NET 3.5+ and.NET Core (.NET Standard 1.0+)
- Focused but full-featured API
Simply reference Optional.dll and you are good to go!
Optional is also available via NuGet:
PM> Install-Package Optional
Or visit:https://www.nuget.org/packages/Optional/
The core concept behind Optional is derived from two common functional programming constructs, typically referred to as a maybe type and an either type (referred to asOption<T>
andOption<T, TException>
in Optional).
Many functional programming languages disallow null values, as null-references can introduce hard-to-find bugs. A maybe type is a type-safe alternative to null values.
In general, an optional value can be in one of two states: Some (representing the presence of a value) and None (representing the lack of a value). Unlike null, an option type forces the user to check if a value is actually present, thereby mitigating many of the problems of null values.Option<T>
is a struct in Optional, making it impossible to assign a null value to an option itself.
Further, an option type is a lot more explicit than a null value, which can make APIs based on optional values a lot easier to understand. Now, the type signature will indicate if a value can be missing!
An either type is conceptually similar to a maybe type. Whereas a maybe type only indicates if a value is present or not, an either type contains an auxiliary value describing how an operation failed. Apart from thisexceptional value, an either-type behaves much like its simpler counterpart.
Working with maybe and either types is very similar, and the description below will therefore focus on the maybe type, and only provide a quick summary for the either type.
Finally, Optional offers several utility methods that make it easy and convenient to work with both of the above described optional values.
To use Optional simply import the following namespace:
usingOptional;
A few auxiliary namespaces are provided:
usingOptional.Linq;// Linq query syntax supportusingOptional.Unsafe;// Unsafe value retrieval
The most basic way to create optional values is to use the staticOption
class:
varnone=Option.None<int>();varsome=Option.Some(10);
For convenience, a set of extension methods are provided to make this a little less verbose:
varnone=10.None();// Creates a None value, with 10 determining its type (int)varsome=10.Some();
Note that it is also allowed (but hardly recommended) to wrap null values in an Option instance:
stringnullString=null;varsomeWithNull=nullString.Some();
To make it easier to filter away such null values, a specialized extension method is provided:
stringnullString=null;varnone=nullString.SomeNotNull();// Returns None if original value is null
Similarly, a more general extension method is provided, allowing a specified predicate:
stringstr="abc";varnone=str.SomeWhen(s=>s=="cba");// Return None if predicate is violatedvarnone=str.NoneWhen(s=>s=="abc");// Return None if predicate is satisfied
Clearly, optional values are conceptually quite similar to nullables. Hence, a method is provided to convert a nullable into an optional value:
int?nullableWithoutValue=null;int?nullableWithValue=2;varnone=nullableWithoutValue.ToOption();varsome=nullableWithValue.ToOption();
When retrieving values, Optional forces you to consider both cases (that is if a value is present or not).
Firstly, it is possible to check if a value is actually present:
varhasValue=option.HasValue;
If you want to check if an option contains a specific value, you can use theContains
orExists
methods. The former checks if the optional contains a specified value, the latter if the contained value satisfies some predicate:
varisThousand=option.Contains(1000);varisGreaterThanThousand=option.Exists(val=>val>1000);
The most basic way to retrieve a value from anOption<T>
is the following:
// Returns the value if present, or otherwise an alternative value (10)varvalue=option.ValueOr(10);varvalue=option.ValueOr(()=>SlowOperation());// Lazy variant
In more elaborate scenarios, theMatch
method evaluates a specified function:
// Evaluates one of the provided functions and returns the resultvarvalue=option.Match(x=>x+1,()=>10);// Or written in a more functional'ish style (think pattern matching)varvalue=option.Match(some: x=>x+1,none:()=>10);
There is a similarMatch
function to simply induce side-effects:
// Evaluates one of the provided actionsoption.Match(x=>Console.WriteLine(x),()=>Console.WriteLine(10));// Or pattern matching'ish as beforeoption.Match(some: x=>Console.WriteLine(x),none:()=>Console.WriteLine(10));
Finally, side-effect matching (that is matching without returning a value) can be carried out for each case separately:
// Evaluated if the value is presentoption.MatchSome(x=>{Console.WriteLine(x)});// Evaluated if the value is absentoption.MatchNone(()=>{Console.WriteLine("Not found")});
In some cases you might be absolutely sure that a value is present. Alternatively, the lack of a value might be fatal to your program, in which case you just want to indicate such a failure.
In such scenarios, Optional allows you to drive without a seatbelt. However, to stress the lack safety, another namespace needs to be imported:
usingOptional.Unsafe;
When imported, values can be retrieved unsafely as:
varvalue=option.ValueOrFailure();varanotherValue=option.ValueOrFailure("An error message");
In case of failure anOptionValueMissingException
is thrown.
In a lot of interop scenarios, it might be necessary to convert an option into a potentially null value. Once the Unsafe namespace is imported, this can be done relatively concisely as:
varvalue=option.ValueOrDefault();// value will be default(T) if the option is empty.
Similarly, it is possible to convert an option into to a nullable (insofar as the inner value is a value type):
varnullable=option.ToNullable();
As a rule of thumb, such conversions should be performed only just before the nullable value is needed (e.g. passed to an external library), to minimize and localize the potential for null reference exceptions and the like.
A few extension methods are provided to safely manipulate optional values.
TheOr
function makes it possible to specify an alternative value. If the option is none, a some instance will be returned:
varnone=Option.None<int>();varsome=none.Or(10);// A some instance, with value 10varsome=none.Or(()=>SlowOperation());// Lazy variant
Similarly, theElse
function enables you to specify an alternative option, which will replace the current one, in case no value is present. Notice, that both options might be none, in which case a none-option will be returned:
varnone=Option.None<int>();varsome=none.Else(10.Some());// A some instance, with value 10varsome=none.Else(Option.None<int>());// A none instancevarsome=none.Else(()=>Option.Some<int>());// Lazy variant
TheMap
function transforms the inner value of an option. If no value is present none is simply propagated:
varnone=Option.None<int>();varstillNone=none.Map(x=>x+10);varsome=10.Some();varsomePlus10=some.Map(x=>x+10);
TheFlatMap
function chains several optional values. It is similar toMap
, but the return type of the transformation must be another optional. If either the resulting or original optional value is none, a none instance is returned. Otherwise, a some instance is returned according to the specified transformation:
varnone=Option.None<int>();varstillNone=none.FlatMap(x=>x.Some());// Returns another Option<int>varsome=10.Some();varstillSome=some.FlatMap(x=>x.Some());varnone=some.FlatMap(x=>x.None());// Turns empty, as it maps to none
FlatMap
is useful in combination with methods that return optional values themselves:
publicstaticOption<Person>FindPersonById(intid){ ...}publicstaticOption<Hairstyle>GetHairstyle(Personperson){ ...}varid=10;varperson=FindPersonById(id);varhairstyle=person.FlatMap(p=>GetHairstyle(p));hairstyle.Match( ...);
In case you end up with a nested optional (e.g.Option<Option<T>>
), you might flatten it by flatmapping it onto itself, but a dedicatedFlatten
function is offered for convenience:
Option<Option<T>>nestedOption= ...Option<T>option=nestedOption.Flatten();// same as nestedOption.FlatMap(o => o)
Finally, it is possible to perform filtering. TheFilter
function returns none, if the specified predicate is not satisfied. If the option is already none, it is simply returned as is:
varnone=Option.None<int>();varstillNone=none.Filter(x=>x>10);varsome=10.Some();varstillSome=some.Filter(x=>x==10);varnone=some.Filter(x=>x!=10);
A recurring scenario, when working with null-returning APIs, is that of filtering away null values after a mapping. To ease the pain, a specificNotNull
filter is provided:
// Returns none if the parent node is nullvarparent=GetNode().Map(node=>node.Parent).NotNull();
An option implementsGetEnumerator
, allowing you to loop over the value, as if it was a collection with either a single or no elements.
foreach(varvalueinoption){Console.WriteLine(value);}
As you might have noticed, this is a nice and lightweight alternative toMatch
in cases where you only want to do something if the value is present. Also, you should use this instead of the more verbose and unsafe combination ofoption.HasValue
andoption.ValueOrFailure()
, which you might otherwise be tempted to try.
Notice, however, that options don't actually implementIEnumerable<T>
, in order to not pollute the options with LINQ extension methods and the like. Although many LINQ methods share functionality similar to those offered by an option, they offer a more collection-oriented interface, and includes several unsafe functions (such asFirst
,Single
, etc).
Although options deliberately don't act as enumerables, you can easily convert an option to an enumerable by calling theToEnumerable()
method:
varenumerable=option.ToEnumerable();
Optional supports LINQ query syntax, to make the above transformations somewhat cleaner.
To use LINQ query syntax you must import the following namespace:
usingOptional.Linq;
This allows you to do fancy stuff such as:
varpersonWithGreenHair=frompersoninFindPersonById(10)fromhairstyleinGetHairstyle(person)fromcolorinParseStringToColor("green")wherehairstyle.Color==colorselectperson;
In general, this closely resembles a sequence of calls toFlatMap
andFilter
. However, using query syntax can be a lot easier to read in complex cases.
Two optional values are equal if the following is satisfied:
- The two options have the same type
- Both are none, both contain null values, or the contained values are equal
An option both overridesobject.Equals
and implementsIEquatable<T>
, allowing efficient use in both generic and untyped scenarios. The==
and!=
operators are also provided for convenience. In each case, the semantics are identical.
The generated hashcodes also reflect the semantics described above.
Further, options implementIComparable<T>
and overload the corresponding comparison operators (< > <= >=
). The implementation is consistent with the above described equality semantics, and comparison itself is based on the following rules:
- An empty option is considered less than a non-empty option
- For non-empty options comparison is delegated to the default comparer and applied on the contained value
As described above, Optional support the notion of an either type, which adds and exception value, indicating how an operation went wrong.
AnOption<T, TException>
can be created directly, just like theOption<T>
. Unlike in this simple case, we need to specify potential exceptional values (and a lot of verbose type annotations - sorry guys):
varnone=Option.None<int,ErrorCode>(ErrorCode.GeneralError);varsome=Option.Some<int,ErrorCode>(10);// These extension methods are hardly useful in this case,// but here for consistencyvarnone=10.None(ErrorCode.GeneralError);varsome=10.Some<int,ErrorCode>();stringstr="abc";varnone=str.SomeWhen(s=>s=="cba",ErrorCode.GeneralError);varnone=str.SomeWhen(s=>s=="cba",()=>SlowOperation());// Lazy variantstringnullString=null;varnone=nullString.SomeNotNull(ErrorCode.GeneralError);varnone=nullString.SomeNotNull(()=>SlowOperation());// Lazy variantint?nullableWithoutValue=null;int?nullableWithValue=2;varnone=nullableWithoutValue.ToOption(ErrorCode.GeneralError);varsome=nullableWithValue.ToOption(ErrorCode.GeneralError);varsome=nullableWithValue.ToOption(()=>SlowOperation());// Lazy variant
Retrieval of values is very similar as well:
varhasValue=option.HasValue;varisThousand=option.Contains(1000);varisGreaterThanThousand=option.Exists(val=>val>1000);varvalue=option.ValueOr(10);varvalue=option.ValueOr(()=>SlowOperation());// Lazy variantvarvalue=option.ValueOr(exception=>(int)exception);// Mapped from exceptional value// If the value and exception is of identical type,// it is possible to return the one which is presentvarvalue=option.ValueOrException();
TheMatch
methods include the exceptional value in the none-case:
varvalue=option.Match(some: value=>value+1,none: exception=>(int)exception);option.Match(some: value=>Console.WriteLine(value),none: exception=>Console.WriteLine(exception));option.MatchSome(value=>Console.WriteLine(value));option.MatchNone(exception=>Console.WriteLine(exception));
And again, whenOptional.Unsafe
is imported, it is possible to retrieve the value without safety:
varvalue=option.ValueOrFailure();varanotherValue=option.ValueOrFailure("An error message");varpotentiallyNullValue=option.ValueOrDefault();
Values can be conveniently transformed using similar operations to that of theOption<T>
. It is however important to note, that these transformations are allshort-circuiting! That is, if an option is already none, the current exceptional value will remain, and not be replaced by any subsequent filtering. In this respect, this exceptional value is very similar to actual exceptions (hence the name).
varnone=Option.None<int,ErrorCode>(ErrorCode.GeneralError);varsome=none.Or(10);varsome=none.Or(()=>SlowOperation());// Lazy variantvarsome=none.Or(exception=(int)exception);// Mapped from exceptional valuevarsome=none.Else(10.Some<int,ErrorCode>());// A some instance with value 10varsome=none.Else(Option.None<int,ErrorCode>(ErrorCode.FatalError));// A none instance carrying a ErrorCode.FatalErrorvarsome=none.Else(()=>10.Some<int,ErrorCode>());// Lazy variantvarsome=none.Else(exception=Option.None<int,ErrorCode>(exception));// Mapped from exceptional value// Mappingvarnone=Option.None<int,ErrorCode>(ErrorCode.GeneralError);varstillNone=none.Map(x=>x+10);varsome=Option.Some<int,ErrorCode>(10);varsomePlus10=some.Map(x=>x+10);// Flatmappingvarnone=Option.None<int,ErrorCode>(ErrorCode.GeneralError);varstillNone=none.FlatMap(x=>x.Some<int,ErrorCode>());varsome=Option.Some<int,ErrorCode>(10);varstillSome=some.FlatMap(x=>x.Some<int,ErrorCode>());varnone=some.FlatMap(x=>x.None(ErrorCode.GeneralError));Option<Option<int,ErrorCode>,ErrorCode>nestedOption= ...Option<int,ErrorCode> option=nestedOption.Flatten();// Filteringvarresult=Option.Some<int,ErrorCode>(10).Filter(x=>true,ErrorCode.GeneralError)// Stil some.Filter(x=>false,ErrorCode.GeneralError)// Now "GeneralError".Filter(x=>false,ErrorCode.IncorrectValue)// Still "GeneralError".Filter(x=>false,()=>SlowOperation());// Lazy variantvarresult=Option.Some<string,ErrorCode>(null).NotNull(ErrorCode.GeneralError)// Returns none if the contained value is null.NotNull(()=>SlowOperation());// Lazy variant
Enumeration works identically to that ofOption<T>
:
foreach(varvalueinoption){// Do something}varenumerable=option.ToEnumerable();
LINQ query syntax is supported, with the notable exception of thewhere
operator (as it doesn't allow us to specify an exceptional value to use in case of failure):
varoptionalDocument=fromfileinuser.GetFileFromDatabase()fromdocumentinFetchFromService(file.DocumentId)selectdocument;optionalDocument.Match(some: document=>Console.WriteLine(document.Contents),none: errorCode=>Console.WriteLine(errorCode));
To make interop betweenOption<T>
andOption<T, TException>
more convenient, several utility methods are provided for this purpose.
The most basic of such operations, is to simply convert between the two types:
varsome=Option.Some("This is a string");// To convert to an Option<T, TException>, we need to tell which// exceptional value to use if the current option is nonevarsomeWithException=some.WithException(ErrorCode.GeneralError);varsomeWithException=some.WithException(()=>SlowOperation());// Lazy variant// It is easy to simply drop the exceptional valuevarsomeWithoutException=someWithException.WithoutException();
When flatmapping, it is similarly possible to flatmap into a value of the other type:
// The following flatmap simply ignores the new exceptional valuevarsome=Option.Some("This is a string");varnone=some.FlatMap(x=>x.None(ErrorCode.GeneralError));// The following flatmap needs an explicit exceptional value// as a second argumentvarsome=Option.Some<string,ErrorCode>("This is a string");varnone=some.FlatMap(x=>Option.None<string>(),ErrorCode.GeneralError);varnone=some.FlatMap(x=>Option.None<string>(),()=>SlowOperation());// Lazy variant
Optional provides a few convenience methods to ease interoperability with common .NET collections, and improve null safety a bit in the process.
LINQ provides a lot of useful methods when working with enumerables, but methods such asFirstOrDefault
,LastOrDefault
,SingleOrDefault
, andElementAtOrDefault
, all return null (more preciselydefault(T)
) to indicate that no value was found (e.g. if the enumerable was empty). Optional provides a safer alternative to all these methods, returning an option to indicate success/failure instead of nulls. As an added benefit, these methods work unambiguously for non-nullable/structs types as well, unlike their LINQ counterparts.
varoption=values.FirstOrNone();varoption=values.FirstOrNone(v=>v!=0);varoption=values.LastOrNone();varoption=values.LastOrNone(v=>v!=0);varoption=values.SingleOrNone();varoption=values.SingleOrNone(v=>v!=0);varoption=values.ElementAtOrNone(10);
(Note that unlikeSingleOrDefault
,SingleOrNone
never throws an exception but returns None in all "invalid" cases. This slight deviation in semantics was considered a safer alternative to the existing behavior, and is easy to work around in practice, if the finer granularity is needed.)
Optional provides a safe way to retrieve values from a dictionary:
varoption=dictionary.GetValueOrNone("key");
GetValueOrNone
behaves similarly toTryGetValue
on anIDictionary<TKey, TValue>
orIReadOnlyDictionary<TKey, TValue>
, but actually supports anyIEnumerable<KeyValuePair<TKey, TValue>>
(falling back to iteration, when a direct lookup is not possible).
Another common scenario, is to perform various transformations on an enumerable and ending up with a sequence of options (e.g.IEnumerable<Option<T>>
). In many cases, only the non-empty options are relevant, and as such Optional provides a convenient method to flatten a sequence of options into a sequence containing all the inner values (whereas empty options are simply thrown away):
varoptions=newList<Option<int>>{Option.Some(1),Option.Some(2),Option.None<int>()};varvalues=option.Values();// IEnumerable<int> { 1, 2 }
When working with a sequence ofOption<T, TException>
a similar method is provided, as well a way to extract all the exceptional values:
varoptions=GetOptions();// IEnumerable<Option<int, string>> { Some(1), None("error"), Some(2) }varvalues=options.Values();// IEnumerable<int> { 1, 2 }varexceptions=options.Exceptions();// IEnumerable<string> { "error" }
About
A robust option type for C#
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors6
Uh oh!
There was an error while loading.Please reload this page.