Consider that I have the following 3 classes / interfaces:
class MyClass<T> { } interface IMyInterface { } class Derived : IMyInterface { }
And I want to be able to use MyClass<Derived> in MyClass<IMyInterface> or vice versa:
MyClass<Derived> a = new MyClass<Derived>(); MyClass<IMyInterface> b = (MyClass<IMyInterface>)a;
But I get compiler errors if I try:
Cannot convert type 'MyClass<Derived>' to 'MyClass<IMyInterface>'
I am sure there is a very good reason why I cannot do this, but I cannot come up with this.
Why do I want to do this? The scenario I present is one in which you ideally want to work with an instance of MyClass<Derived> to avoid a lot of unpleasant throws, however you need to pass your instance an interface that accepts MyClass<IMyInterface> .
So my question is twofold:
- Why can't I use these two types?
- Is there a way to preserve the superiority of working with an instance of
MyClass<Derived> , although it is still able to pass this to MyClass<IMyInterface> ?
generics casting c # covariance
Justin
source share