What is the difference between <out T> and <T>? For example:
public interface IExample<out T>
{
...
}
vs.
public interface IExample<T>
{
...
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
outkeyword in generics is used to denote that the type T in the interface is covariant. See Covariance and contravariance for details.The classic example is
IEnumerable<out T>. SinceIEnumerable<out T>is covariant, you’re allowed to do the following:The second line above would fail if this wasn’t covariant, even though logically it should work, since string derives from object. Before variance in generic interfaces was added to C# and VB.NET (in .NET 4 with VS 2010), this was a compile time error.
After .NET 4,
IEnumerable<T>was marked covariant, and becameIEnumerable<out T>. SinceIEnumerable<out T>only uses the elements within it, and never adds/changes them, it’s safe for it to treat an enumerable collection of strings as an enumerable collection of objects, which means it’s covariant.This wouldn’t work with a type like
IList<T>, sinceIList<T>has anAddmethod. Suppose this would be allowed:You could then call:
This would, of course, fail – so
IList<T>can’t be marked covariant.There is also, btw, an option for
in– which is used by things like comparison interfaces.IComparer<in T>, for example, works the opposite way. You can use a concreteIComparer<Foo>directly as anIComparer<Bar>ifBaris a subclass ofFoo, because theIComparer<in T>interface is contravariant.