How is IEnumerable <T> Contra-variant?

This post ( http://blogs.msdn.com/b/brada/archive/2005/01/18/355755.aspx ) says that IEnumerable<T> Contra-variant. However, type T is a co-option because it is an out parameter. So, in what context is IEnumerable<T> Contra-variant ??

I hope I'm not embarrassed! Thanks for the answers in advance!

+4
source share
1 answer

IEnumerable is not contravariant. This is covariant.

From MSDN (IEnumerable <(Of <(T>)>)) we have that:

Type parameters

out T

The type of objects to enumerate. This type parameter is covariant . That is, you can use either the type you specified or any type that is more derived.

From this post we have the following:

The base class library has been updated to support covariance and contravariance in the various interfaces used. For example, IEnumerable is now a covariant interface - IEnumerable.

Code example:

 // Covariant parameters can be used as result types interface IEnumerator<out T> { T Current { get; } bool MoveNext(); } // Covariant parameters can be used in covariant result types interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } // Contravariant parameters can be used as argument types interface IComparer<in T> { bool Compare(T x, T y); } 

For more examples, see:

Questions of covariance and contravariance

Covariance and contravariance in C #, part one (Eric Lippert's Big Series of Messages on Covariance and Contravariance)

Understanding C # Covariance and Contravariance (3) Samples

+9
source

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


All Articles