Possible Duplicate:
Why was IEnumerable<T> made covariant in C# 4?
I was taking a look on MSDN for IEnumerable<T> interface definition, and see:
public interface IEnumerable<out T> : IEnumerable
I was wondering why T is defined as out, why not?
public interface IEnumerable<T> : IEnumerable
What is the reason for this?
More information can be found here.
The
outmakes the type parameter covariant. That is, you can use either the type or any derived types. Note thatoutonly works this way with generics, it has a different meaning when used in method signatures (though you probably already knew that).Here is the example taken from the referenced page:
As you can see, the
outin the interface signature allowsyou to assign an
ICovariant<String>to anICovariant<Object>variable, asStringderives fromObject. Without theoutkeyword, you would be unable to do this, as the types would be different.You can read more about covariance (and the related contravariance) here.
As other answers have pointed out,
IEnumerablewas only made covariant in .NET 4. Trying to write code such as:will compile in .NET 4 and later versions, but not in previous versions.