Can I cast
IInterface<MyClass>
to
IInterface<IAnother>
when MyClass implements IAnother?
Can I cast
IInterface<MyClass>
to
IInterface<IAnother>
when MyClass implements IAnother?
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.
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.