NOption is a concise and fluent implementation of the Option pattern for the .NET platform.
Simply import the NOption namespace:
import NOption;
To start using NOption:
- Change your function return type to Option<>;
- The return value will implicitely be wrapped in an Option<>;
- To specify that there is no return value, use Option.None.
static Option<Color> GetFavoriteColor(string username)
{
if ("Emma".Equals(username))
{
return Option.Some(Color.Blue);
}
return Option.None<Color>();
}
To work with result, you can use Match:
var result = GetFavoriteColor("Emma");
result.Match(
Some: (favoriteColor) => Console.WriteLine($"Emma likes the color {favoriteColor}."),
None: () => Console.WriteLine("Emma does not have a favorite color.")
);
// Print "Emma likes the color Blue"
You can also unwrap the content with a default value:
var result = GetFavoriteColor("Mark");
var favoriteColor = result.UnwrapOr(Color.Purple); // Returns Color.Purple
Or you can extract the value:
var result = GetFavoriteColor("Emma");
if (result.HasSome(out var favoriteColor))
{
Console.WriteLine($"Emma likes the color {favoriteColor}.");
}
To rewrite GetFavoriteColor as a one line function, we could have use:
static Option<Color> GetFavoriteColor(string username)
{
return Option.Some(Color.Blue, when: "Emma".Equals(username));
}