Casting generics and the generic type

Posted by Kragen on Stack Overflow See other posts from Stack Overflow or by Kragen
Published on 2010-04-19T23:54:04Z Indexed on 2010/04/20 0:03 UTC
Read the original article Hit count: 487

Filed under:
|
|

Consider, I have the following 3 classes / interfaces:

class MyClass<T> { }

interface IMyInterface { }

class Derived : IMyInterface { }

And I want to be able to cast a MyClass<Derived> into a MyClass<IMyInterface> or visa-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'm sure there is a very good reason why I cant do this, but I can't think of one.

As for why I want to do this - The scenario I'm imagining is one whereby you ideally want to work with an instance of MyClass<Derived> in order to avoid lots of nasty casts, however you need to pass your instance to an interface that accepts MyClass<IMyInterface>.

So my question is twofold:

  • Why can I not cast between these two types?
  • Is there any way of keeping the niceness of working with an instance of MyClass<Derived> while still being able to cast this into a MyClass<IMyInterface>?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics