DEV Community

loading...
Cover image for A Simple `Option` Object for C# 9

A Simple `Option` Object for C# 9

sharpninja profile image The Sharp Ninja ・1 min read

C# 9 brings lots of new features to make C# more "Functional." One of those is immutable record types, but did you know that records can have extended functionality, not just hold immutable data?

Functional languages often use the Optional Monad pattern to prevent null reference checks. Combining C# 9's record with a switch expression allows us to easily create a simple Option<T> object.

using static System.Console;

WriteLine(TryDivision(10,2));
WriteLine(TryDivision(10,0));

static Option<int> CheckedDivision(int dividend, int divisor)
    => divisor == 0
        ? Option<int>.None
        : Option<int>.Some(dividend / divisor);

static string TryDivision(int dividend, int divisor)
{
    var quotient = CheckedDivision(dividend, divisor);
    return quotient switch
    {
        Option<int>.None => $"{dividend} / {divisor} failed!",
        _ => $"{dividend} / {divisor} = {quotient}"
    };
}

public record Option<T>(T value)
{
    public const Option<T> None = default;
    public static Option<T> Some(T value) => new (value);
    public override string ToString() => value.ToString();
}
Enter fullscreen mode Exit fullscreen mode

This code also uses another new feature of C# 9 to reduce boilerplate. Go ahead and throw it into .Net Fiddle (or let me do it for you) and check it out!

Discussion (0)

pic
Editor guide