Using C#/.NET 4.0 I was hoping the following scenario would be possible:
interface IA<out TB> where TB : IB { }
interface IB { }
class A<TB> : IA<TB> where TB : IB { }
class B : IB { }
abstract class AbstractA<TB> : IA<TB> where TB : IB { }
class DerivedA<TB> : AbstractA<TB> where TB : IB { }
static void Main(string[] args) {
var myAB = new A<B>();
Debug.Assert(myAB is IA<B>); // fine
Debug.Assert(myAB is IA<IB>); // fine
var myDerivedAB = new DerivedA<B>();
Debug.Assert(myDerivedAB is IA<IB>); // fine
Debug.Assert(myDerivedAB is DerivedA<B>); // fine
Debug.Assert(myDerivedAB is DerivedA<IB>); // NOT fine
}
Sadly the last test fails, although the types clearly are compatible. Would there be another way to test this, other than testing for every known implementation of IB?
class FirstB : IB { }
class SecondB : IB { }
Debug.Assert(myDerivedAB is DerivedA<FirstB> || myDerivedAB is DerivedA<SecondB>)
You can use GetGenericArguments method of Type object:
By this you can get the Generic parameter of the
myDerivedABobject, and check its type, or something else you need.