How to check that T of IEnumerable <T> is IInterface?

Basically, what would be the equivalent of this, but 100% guaranteed to work?

 object x = new List<MyTypeWhichImplementsIInterface>();
 bool shouldBeTrue = x is IEnumerable<IInterface>;

From some rough testing this works, but I'm not sure.

+4
source share
3 answers

This will work in C # 4, but not in previous versions.

The operator isuses covariance for type type parameters added in C # 4. Prior to C # 4, the statement will be false.

+6
source

This works because IEnumerable<T>in fact IEnumerable<out T>. Without a dispersion specifier, <T>this would not work.

, , yout , "T" , .

in/out , T , , , CSJ, .

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

Source: https://habr.com/ru/post/1526063/


All Articles