Implement Your Option Wrapper
Implement a lightweight version of the Option type.
We'll cover the following...
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 ...