Skip to content

Option Type Overview

Jordan Jordanov edited this page Nov 7, 2018 · 8 revisions

An option type or maybe type is a polymorphic type that represents an encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied.

The Option (or Maybe) type has been around for quite some time now and it enables languages like Haskell and Standard ML to completely scratch off the null value. An Option can either have a value or be None. Implementation for C# is called Optional which you can find on GitHub or as a NuGet package.

Example:

Option<Person> GetPerson(int id);

What does this definition tell us?

Well, first, the Option is a value type, therefore it can never be null. Second, knowing that an Option can either have a value or not, we can instantly extract (and with, us, the compiler) that this function will either return a Person or an empty option.

Okay, but the result I got is of type Option and what I need is a Person object, how do I get the underlying value?

Well, the Option type doesn’t really have a method to simply retrieve the value (unless you tap into the Unsafe library) and this is what makes it special. Instead of being given a value accessor, you get a Match function.

Match takes two parameters – some and none.

Some is the function that will be executed if the option has a value, and none is an action that will be executed when it does not.

It looks like this:

`option.Match( some: x => DoSomethingWithTheValue(x), none: () => SignalThatAValueIsMissing());

// Or the generic version

option.Match( some: x => DoSomethingWithTheValueAndReturnT(x), none: () => SignalThatAValueIsMissingAndReturnT());`

This forces you to handle both situations (when a value is present and when not) and avoid corrupt data.

ASP.NET controller example:

public IActionResult Get(int personId) => GetPerson(personId).Match<IActionResult>(Ok, NotFound); // Taking advantage of method groups

Clone this wiki locally