...

/

Implement Your Option Wrapper

Implement Your Option Wrapper

Implement a lightweight version of the Option type.

So far, we have used the Option type as a replacement for null and C# 8.0 nullable references when working with previous versions of the C# language. Also, we learned that C#, unlike functional languages, doesn’t have a built-in Option type. We have to either use a third-party library or write our own Option type. Let’s write our own lightweight Option type to see its inner workings.

Defining the Option class

Let’s start by writing an Option class with the Some(), None(), and Match() methods.

Press + to interact
main.cs
Option.cs
NRE.csproj
var someInt = Option<int>.Some(42);
var message = someInt.Match(
value => $"It has a value. It's {value}",
() => "It doesn't have a value");
Console.WriteLine(message);
// TODO: Create a variable, assign it to None, and
// print its value using Match
// var none = ...

Let’s take a look at the Option.cs file first.

We’re using a generic class to put any object we define inside a box. The Option<T> class has two private properties: _value and _hasValue on lines 3 and 4, respectively. The first one holds the actual content of a box, and the second tells if the box is empty.

We’re not exposing the _value ...