Search code examples
c#genericstypesinterfacetypechecking

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.


Solution

  • 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.