It'sNotALie.
It'sNotALie.

Reputation: 22794

How to check if T from IEnumerable<T> is IInterface?

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

Answers (3)

CSJ
CSJ

Reputation: 3941

x.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
typeof(IInterface).IsAssignableFrom(x.GetType().GetGenericArguments()[0]);

Upvotes: 3

driis
driis

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

quetzalcoatl
quetzalcoatl

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

Related Questions