4

Can I cast

IInterface<MyClass>

to

IInterface<IAnother>

when MyClass implements IAnother?

Baldy
  • 3,621
  • 4
  • 38
  • 60
BrendanS
  • 191
  • 13
  • 1
    Why do you need to do this? What specific problem are you attempting to address? – Bernard Jun 22 '11 at 15:44
  • 1
    possible duplicate of [Covariance and contravariance real world example](http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example) – Daniel A. White Jun 22 '11 at 15:47
  • I'm not familiar with C#, but you can in Java. Should just be something like: `(IInterface)myInstanceOfIInterfaceWithMyClass;` – Patrick Perini Jun 22 '11 at 15:48

3 Answers3

4

Yes, but only if your're using C# 4 (or beyond) and, IInterface is declared as IInterface<out T>.

This is called generic covariance, you can find more information on MSDN, or this (more formal but more understandable) introduction from Bart de Smet.

Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172
1

This is possible in C# 4 via Covariance, provided you decorate your usage scenario correctly (ie: IInterface<out IAnother>).

Note that there are potential side effects to doing this, depending on your interface usage. I recommend reading up on Variance in Generic Interfaces for more details, but the main issue is that it's possible to get yourself into a situation where you can have runtime errors because you're giving up some type safety.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

look at covariance and contravariance in C# 4.0

alexl
  • 6,841
  • 3
  • 24
  • 29