IMPLEMENTING OPTION(AL) VALUES

The basic structure of the class Option<T> is obvious: in addition to a value of type T, it stores a flag that says whether the value has been set. The type is immutable, so it is during construction that this decision is made: does the new instance represent an actual value or “nothing”?

It doesn’t make much sense to create loads of new instances of Option<T> that all represent “nothing” for any given type T. So the “nothing” case is covered by a single instance of the class, which is made available through a public field called None. Here’s what the class may look like at this point (this is not what is actually in FCSlib; read on for that):

public sealed class Option<T> {

  private readonly T value;

  public T Value {

    get { return value; }

  }

  private readonly bool hasValue;

  public bool HasValue {

    get { return hasValue; }

  }

  public bool IsSome {

    get { return hasValue; }

  }

  public bool IsNone {

    get { return !hasValue; }

  }

 

  public Option(T value) {

    this.value = value;

    this.hasValue = true;

  }

 

  private Option( ) {

  }

 

  public static readonly Option<T> None = new Option<T>( );

}

To create an option type instance, the code would look like this now:

var intVal = new Option<int>(42);

var intValNothing = Option<int>.None;

In both cases it is necessary to specify the actual value type explicitly because type inference doesn’t work in these scenarios. It is possible, though, to create a helper function to ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.