Reputation: 22794
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.
Upvotes: 4
Views: 105
Reputation: 3941
x.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
typeof(IInterface).IsAssignableFrom(x.GetType().GetGenericArguments()[0]);
Upvotes: 3
Reputation: 164291
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.
Upvotes: 6
Reputation: 33506
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.
Upvotes: 3