19 Jan, 2009
interface implementing more specific returntype
It’s no secret I really like C#. Not all is happily ever after though:
public interface ICanDoSomething { IAnimal FindAnimal(); } public class Dog : IAnimal { } public class DoSomething : ICanDoSometing { Dog FindAnimal() //I want this to work! { return new Dog(); } }
Why does the FindAnimal method with the Dog returntype not satisfy the interface requirement of having a FindAnimal method that returns an IAnimal? Dog implements IAnimal. So people who
use DoSomething as an ICanDoSomething will get a IAnimal, but if you happen to know that the implementation of your ICanDoSomething is a DoSomething, then you get back a more specific type, that you can call dog-only methods on.
The same would go for allowing less specific method arguments. If the interface defines SomeMethod(Dog d), but I want my implementation to implement SomeMethod(IAnimal a), I should be allowed to do that.
Very annoying. Like always, I’m sure there actually is a good reason for this somewhere, but that doesn’t make it less annoying
. Maybe this will get addressed with the whole Contravariance/invariance stuff in c#4. I can’t wait.
Anybody got an elegant workaround for this in the meantime?