Amplify C#

Recently, while following the coursera course on reactive programming and especially Erik Meijer’s introduction to Scala I’ve got interested in some monad types Scala has to offer. What monads are, has already extensively been described on the web. For example Wes Dyer or Eric Lippert offer excellent explanations.
In the following posts I want to have a closer look at Scala’s Option and how it could be ported to C#. The amplification (a term coined in Wes Dyer’s blog post) behind Option is nothing new to C# developers: For a certain type it either holds some or none value of that type. A functionality which is already available with the class Nullable of T in C#. Unfortunately Nullable of T is restricted to value types – It cannot be used with reference types. Of course people have written their own Nullable implementations which allow T to be a reference type as well but my goal is to learn about the inner mechanics of such a Nullable/Maybe/Option type rather than re-using an existing one.

Flattr this!

Flip ‘where’ inheritance constraint for generic methods

The MSDN provides an example for a generic method in C# with a constraint on the generic type of the method. It must derive from T which is the generic type of the surrounding class Bar.

class Bar<T>
{
    void Foo<U>(Data<U> data) where U : T {/*...*/}
}

However it is not possible to compile:

class Bar<T>
{
    void Foo<U>(Data<U> data) where T : U {/*...*/}
}

Which is setting the constraint that U must be a base class of T.
With a little trick it is still possible to have that generic type constraint: by using an extension method.

class Bar<T>
{
    /*...*/
}

class BarExtension
{
   void Foo<T,U>(this Bar<T> bar, Data<U> data) where T : U {/*...*/}
}

Of course this is not as nice as having that method where it belongs to (in the Bar class) but still better than doing a runtime type check.

Flattr this!