More information can be found here.
The out
makes the type parameter covariant. That is, you can use either the type or any derived types. Note that out
only 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:
// Covariant interface.
interface ICovariant<out R> { }
// Extending covariant interface.
interface IExtCovariant<out R> : ICovariant<R> { }
// Implementing covariant interface.
class Sample<R> : ICovariant<R> { }
class Program
{
static void Test()
{
ICovariant<Object> iobj = new Sample<Object>();
ICovariant<String> istr = new Sample<String>();
// You can assign istr to iobj because
// the ICovariant interface is covariant.
iobj = istr;
}
}
As you can see, the out
in the interface signature allows
you to assign an ICovariant<String>
to an ICovariant<Object>
variable, as String
derives from Object
. Without the out
keyword, 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, IEnumerable
was only made covariant in .NET 4. Trying to write code such as:
IEnumerable<Object> strings = new List<string>();
will compile in .NET 4 and later versions, but not in previous versions.