Variance
Covariance: out T
Variance is the rule for converting one generic type into another when their type arguments are related. Covariance allows IEnumerable<string> where IEnumerable<object> is expected, because a sequence that only gives items out can safely be read as a sequence of a base type:
IEnumerable<string> strings = new List<string> { "Anna", "Borys" };
IEnumerable<object> objects = strings;
Console.WriteLine(string.Join(", ", objects));
Console.WriteLine($"count {objects.Count()}");
IEnumerable<object> mixed = new object[] { 1, "two", 3.0 };
foreach (var item in mixed)
{
Console.WriteLine($"{item.GetType().Name}");
}
dotnet run
Anna, Borys
count 2
Int32
String
Double
The interface is declared IEnumerable<out T>, and the out is the permission for that conversion. Only an output position may use it: a method that returns T is fine, a method that takes a T would not be, since a caller could then pass an int to something that promised strings.
Contravariance: in T
Contravariance is the other direction: a delegate that accepts an object can stand where one accepting a string is expected, because whatever it is given, it can handle.
Action<string> print = s => Console.WriteLine($"string {s}");
Action<object> printAny = o => Console.WriteLine($"object {o}");
print = printAny;
print("hello");
Console.WriteLine($"print is {print.GetType().Name}");
dotnet run
object hello
print is Action`1
The variable is still an Action<string>, and the method it holds is the one for object. The declaration of the delegate is Action<in T>, so the conversion is allowed in the direction that puts the wider parameter type in the narrower slot.
Invariance and the error
A collection that both reads and writes cannot be variant, and List<T> is exactly that. Allowing the conversion would let an int into a list of strings:
List<object> list = new List<string> { "a" };
Console.WriteLine(list.Count);
dotnet build
Program.cs(1,21): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<object>'
Build FAILED.
Program.cs(1,21): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<object>'
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:09.50
The message says only that the conversion cannot be implicit, which is the same CS0029 as an int assigned to a string. The workaround is to convert the items rather than the collection: list.Cast<object>().ToList(), which copies, or to type the variable as IEnumerable<object>, which is covariant and read-only.
Declaring variance on your own type
An interface or a delegate declares its own variance with out and in on the type parameter. A factory only produces its type, so it can be covariant:
IFactory<Animal> factory = new CatFactory();
Animal animal = factory.Create();
Console.WriteLine(animal.Name);
Console.WriteLine($"factory {factory.GetType().Name}");
interface IFactory<out T>
{
T Create();
}
class Animal(string name)
{
public string Name => name;
}
class Cat(string name) : Animal(name)
{
}
class CatFactory : IFactory<Cat>
{
public Cat Create() => new Cat("Mochi");
}
dotnet run
Mochi
factory CatFactory
A CatFactory was used as an IFactory<Animal> without a cast, and the object it created is still a Cat. A method that takes an IFactory of animals can therefore be given a factory of cats, which is the situation variance exists for.
Exercises
- Add an IReadOnlyList<string> and assign it to an IReadOnlyList<object>. Does it compile?
- Try IEnumerable<string> s = (IEnumerable<string>)objects on the mixed array of the first program and read the exception.
- Declare a contravariant interface with in T that takes a value, and use it for two related types.
- Put out on a type parameter that a method also accepts and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does covariance allow?
Answer
Using a sequence of a derived type where a base type is expected
An out type parameter only produces values, so the wider use is safe.
-
Which declaration makes IEnumerable<T> covariant?
Answer
IEnumerable<out T>
out marks the parameter as an output position, which is what covariance needs.
-
What does this program print?
IEnumerable<string> s = new[] { "a", "b" }; IEnumerable<object> o = s; Console.WriteLine(o.Count());Answer
2
The assignment is allowed by covariance and the count is two.
-
What does contravariance allow?
Answer
Using a delegate that accepts a base type where one accepting a derived type is expected
The delegate can handle anything the narrower slot gives it, so the substitution is safe.
-
Why is List<T> invariant?
Answer
It both reads and writes T, so a conversion could put a wrong type in
A writable collection of objects would accept an int into a list of strings.
-
What does this program print?
Action<object> any = o => Console.WriteLine($"got {o}"); Action<string> s = any; s("x");Answer
got x
Contravariance lets the object handler stand in for the string handler.
-
Which error appears when a List<string> is assigned to a List<object>?
Answer
CS0029, a conversion that cannot be implicit
The two constructed types are unrelated as far as the conversion rules go.
-
What may an
outtype parameter appear in?Answer
A return type or a read-only position
Only output positions are allowed, which is what makes the conversion safe.
-
What does this program print?
IEnumerable<object> o = new List<string> { "a" }; foreach (var x in o) Console.WriteLine(x.GetType().Name);Answer
String
Covariance changes the reference type, not the runtime type of the items.
-
Why is an array of string usable as an array of object?
Answer
Array covariance is built into the CLR, and a wrong write throws at run time
Array covariance exists for historical reasons and checks the element type on every write.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev