Revisiting Maybe monad using C# 8.0 Pattern Matching

Dimitris Papadimitriou
2 min readJul 10, 2020

Source Code .NET Fiddle : Maybe Monad Example C# 8.0 Pattern Matching

To be honest i didn't like the pattern matching feature the first time i show it. But i rewrote some sample functional code and i can say i might be a fan.

if you are not familiar with pattern matching read the previous article :

this article revises the Maybe monad seen previously

We will rewrite Maybe using C# 8.0 pattern matching

this is the initial

and now we can just simply replace it with

placing the map definition in the base class

public abstract class Maybe<T>
{
public Maybe<T1> Map<T1>(Func<T, T1> f) =>
this switch
{
None<T> { } => new None<T1>(),
Some<T> { Value: var v } => new Some<T1>(f(v)),
};
}

and we can use it like this :

var result = new Some<int>(4)
.Map(v => $"number is : {v}")
switch //another switch to extract the value
{
None<string> { } => "Not found",
Some<string> { Value: var v } => "some" + 5,
_ => throw new NotImplementedException(),
};

we can similarly define the Bind :

here i used extension methods but we can put that also in the base class Maybe<T>.

Practical functional C#

--

--