Covariance and Contravariance
In this page:
Covariance and Contravariance
Covariance (out T) lets a generic interface with a more derived type be used where a less derived type is expected, like treating IEnumerable<string> as IEnumerable<object>. Contravariance (in T) works the opposite direction for input positions, like delegates. These annotations only apply to interfaces and delegates, not classes, and only make sense for reference types.
Note: IEnumerable<T> is covariant, which is why you can pass a List<string> anywhere an IEnumerable<object> is expected.
Example: Covariance and Contravariance
using System;
using System.Collections.Generic;
class Program
{
static void PrintAll(IEnumerable<object> items)
{
foreach (object item in items)
{
Console.WriteLine(item);
}
}
static void Main(string[] args)
{
List<string> names = new List<string> { "Ana", "Bo" };
PrintAll(names); // covariance: IEnumerable<string> used as IEnumerable<object>
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: