Sunday, January 11, 2015

Yet another Option type for C#

Having been bitten again recently by some code which could contain null as a meaningful value, I set down and put together my own variation on this theme. Unlike the first hit I got for "c# option type", which when faced with the question of whether you could have a Just null, went with "Yes." that on the basis of an example with meaningful nulls (getting the first element if any of a sequence that might contain nulls), I'm going to say that the whole motivation for such a type is to avoid the trap of meaningful nulls, and if you occasionally need a transient Maybe<Maybe<T>>, that should represent an edge case which you'd expect to need handle with care anyway.

The constraints of the C# language mean that there isn't a perfect representation -- we need a struct to avoid any null values of the null-eliminating type, but that means we can't inherit to distinguish cases with and without value, or initialize fields, which means we have to explicitly do at runtime what we would do by virtual method calls.

Inside the struct, I just build on the well known dodge of using null-object IEnumerable-as-Maybe idea; which also allows us to access the vast number of Enumerable extension methods to augment the type. So we start out with

The first two serve to move the generic from the type to the function name; then we have a series of conversions that invert or augment ones that we already have. Analogues of any further Enumerable extension methods desired can now be written in the form AsEnumerable.EnumerableExtensionMethodReturningIEnumerable().ToMaybe() -- the one that I see as most likely to see heavy use being OfType<T>() to conditionally extract the value as a subtype.

Post a Comment