Things I’d like to see in C#: Conditional interface implementation
To explain this, imagine you are designing a type Wrapper<T>, which is just a simple wrapper around a type T.
class Wrapper<T> { T value; public Wrapper(T theObject) { value = theObject; } // Some other methods... }
Now, since this is a just a wrapper around some type T, we would like to implement some simple interfaces around this object. For example, if T is comparable, we would like the wrapper class to implement IComparable<Wrapper<T>>. However this is not possible with C#. In Haskell we would have something like this:
instance (Disposable a) => Disposable (Wrapper a) where ...
This says “if a is a type that is an instance of Disposable, then the type Wrapper a is also an instance of Disposable”. In C#, I’d like to see something like this:
class Wrapper<T> : IComparable<Wrapper<T>> when T : IComparable<T> //this is the syntax extension { //... }
And then in any methods that the interface specifies (in this case int Compare(Wrapper<T> other)), it is assumed that for any object of type T you have access to all the methods that T has when it implements IComparable<T>.
At the moment the best you can do is to always implement IComparable<Wrapper<T>> and just throw a runtime exception when T doesn’t implement IComparable<T>, which isn’t very nice.
A simple idea, but it would add great power to C#.
After some (very quick) research I haven’t found anything that suggests anyone else has attempted to get this into C#, but there is JavaGI (see section 2.4 for the equivalent of what this post talks about) where the authors have extended Java to deal with what they term ‘generalized interfaces’—a concept which alters Java (rather radically) to make interface implementations similar to Haskell’s typeclasses.
