Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 510
It'sNotALie. Avatar asked Dec 15 '22 01:12

It'sNotALie.


2 Answers

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.

like image 147
driis Avatar answered Dec 26 '22 10:12

driis


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.

like image 40
quetzalcoatl Avatar answered Dec 26 '22 10:12

quetzalcoatl