Basically, what would be the equivalent of this but is 100% guaranteed to work?
object x = new List<MyTypeWhichImplementsIInterface>();
bool shouldBeTrue = x is IEnumerable<IInterface>;
From some rough testing it seems to work, but I'm not sure.
This will work in C# 4, but not in prior versions.
The is
statement takes advantage of covariance for generic type parameters, a feature added in C# 4. Prior to C# 4, the statement would be false.
It works because the IEnumerable<T>
is actually IEnumerable<out T>
. Without the variance-specifier on the <T>
it wouldn't work.
So, as long as yout interface has correct variance specifiers, and as long as 'T' at both sides satisfy the type of the variance, it's ok.
If there are no in/out
specifiers, then the T must match exactly for the cast to succeed, and the manual check presented by CSJ is the only option left.
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