I have a problem with the is operator comparing generic types.
public interface ISomeInterface<T> where T : SomeBaseClass{
}
public class SomeClass : SomeBaseClass{
}
Now we want to check the type with is operator. We have an instance of a class implementing interface ISomeInterface.
Unfortunatly we are facing following problem:
// someObject is an Instance of a class implementing interface ISomeInterface<SomeClass>
bool isSomeBaseClass = someObject is ISomeInterface<SomeBaseClass>; // false
bool isSomeClass = someObject is ISomeInterface<SomeClass>; // true
Is it possible to check a variable generic type?
Thanks in advance, Tobi
This is called generic covariance and is supported in C# 4.0. You could mark the generic T
parameter with the out
keyword:
public interface ISomeInterface<out T> where T : SomeBaseClass
This has a limitation though. The T
parameter can only appear as return type of the methods in the interface.
Eric Lippert has a series of blog posts on this subject that I invite you to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With