Casting Overview

Can i use

IInterface<MyClass> 

to

 IInterface<IAnother> 

When does MyClass implement IAnother?

+4
source share
3 answers

Yes, but only if your use of C # 4 (or beyond) and IInterface declared as IInterface<out T> .

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

+4
source

This is possible in C # 4 through Covariance if you correctly decorate your use case (for example: IInterface<out IAnother> ).

Please note that there are potential side effects for this, depending on the use of the interface. I recommend reading additional information about โ€œDifferences in Common Interfaces,โ€ but the main problem is that you may end up in a situation where you might have run-time errors because you are giving up any type of security.

+1
source

Look at covariance and contravariance in C # 4.0

+1
source

All Articles