A string is an object. Is a List<string> a List<object>? It feels as if it should be, and the compiler says no. Variance explains why, and when the answer is yes.
Why List can't be converted
If that conversion were allowed, you could add a number through the List<object> variable, into a list that everyone else believes contains only strings. So it's refused at compile time.
List<string> words = new() { "a" };
List<object> items = words;
items.Add(1);Check your prediction
error CS0029out: covariance
IEnumerable<T> only ever hands out T values. You can't add anything through it, so treating a sequence of strings as a sequence of objects is safe. Its real declaration is IEnumerable<out T>, and out is how the interface states that promise. Your own interfaces can use it, and the compiler stops you from using T as an input.
IEnumerable<string> words = new List<string> { "a", "b" };
IEnumerable<object> items = words;
Console.WriteLine(items.Count());
ISource<Dog> dogs = new DogSource();
ISource<Animal> animals = dogs;
Console.WriteLine(animals.Next().Name);
class Animal(string name)
{
public string Name { get; } = name;
}
class Dog(string name) : Animal(name);
interface ISource<out T>
{
T Next();
}
class DogSource : ISource<Dog>
{
public Dog Next() => new Dog("Rex");
}Check your prediction
2
Rexin: contravariance
The opposite applies to things that only take in values. Something that handles any Animal can certainly handle a Dog. So IHandler<Animal> converts to IHandler<Dog>, which looks backwards until you think about who's calling whom. Action<in T> and IComparer<in T> work this way.
IHandler<Animal> general = new NameHandler();
IHandler<Dog> forDogs = general;
forDogs.Handle(new Dog("Rex"));
Action<object> print = value => Console.WriteLine(value);
Action<string> printText = print;
printText("hello");
class Animal(string name)
{
public string Name { get; } = name;
}
class Dog(string name) : Animal(name);
interface IHandler<in T>
{
void Handle(T item);
}
class NameHandler : IHandler<Animal>
{
public void Handle(Animal item)
{
Console.WriteLine(item.Name);
}
}Check your prediction
Rex
helloFunc<in T, out TResult> has both: it takes in T and hands out TResult. An easy way to remember which is which: out for outputs, and in for inputs.
A hole in arrays
Arrays have allowed covariance since before generics existed, so object[] items = new string[1] compiles. The check moves to run time, and storing the wrong type throws. It's a good reason to prefer IReadOnlyList<T> for inputs.
string[] words = { "a" };
object[] items = words;
Console.WriteLine(items[0]);
try
{
items[0] = 1;
}
catch (ArrayTypeMismatchException)
{
Console.WriteLine("refused at run time");
}Check your prediction
a
refused at run timeThe limits
Variance works only on interfaces and delegates, not on classes or structs. It also needs reference types: IEnumerable<int> won't convert to IEnumerable<object>, since an int would have to be boxed and that changes its representation. If you need that conversion, Cast<object>() or Select does it explicitly.
IEnumerable<int> numbers = new[] { 1, 2 };
IEnumerable<object> boxed = numbers.Cast<object>();
Console.WriteLine(boxed.Count());
Console.WriteLine(numbers is IEnumerable<object>);
IEnumerable<string> words = new[] { "a" };
Console.WriteLine(words is IEnumerable<object>);Check your prediction
2
False
TrueYour turn
Design a variant queue
A message bus has two views. Split IQueue<T> into two interfaces, each with suitable variance: IProducer<T> has T Take(), and IConsumer<T> has void Give(T item). A class Line<T> implements both, on top of a Queue<T>.
With a Line<Dog> (the classes Animal and Dog appear in the workspace):
- Assign it to
IProducer<Animal>, and print the name of something taken from it, after giving it a dog namedRex. - Write a
Line<Animal>, assign it toIConsumer<Dog>, give it a dog namedBo, and print the count of the line.
When it works, it prints:
Rex
1var dog = new Dog("Rex");
Console.WriteLine(dog.Name);
class Animal(string name)
{
public string Name { get; } = name;
}
class Dog(string name) : Animal(name);Hint 1: the idea
Take only hands values out, and Give only takes values in. Each interface has one direction, so each can have one variance keyword.
Hint 2: a first step
Declare the interfaces. The compiler tells you if you've chosen the wrong keyword: an out type used as a parameter is error CS1961.
Show one solution
var dogs = new Line<Dog>();
dogs.Give(new Dog("Rex"));
IProducer<Animal> producer = dogs;
Console.WriteLine(producer.Take().Name);
var animals = new Line<Animal>();
IConsumer<Dog> consumer = animals;
consumer.Give(new Dog("Bo"));
Console.WriteLine(animals.Count);
class Animal(string name)
{
public string Name { get; } = name;
}
class Dog(string name) : Animal(name);
interface IProducer<out T>
{
T Take();
}
interface IConsumer<in T>
{
void Give(T item);
}
class Line<T> : IProducer<T>, IConsumer<T>
{
private readonly Queue<T> items = new();
public int Count => items.Count;
public T Take() => items.Dequeue();
public void Give(T item)
{
items.Enqueue(item);
}
}Rex
1Channel<T>, which you'll use on Day 4, follows this same design: it has a separate reader and writer. The library's are classes, so they have no variance, but the split still means that code receives only the half it needs.
Completion is saved in this browser only. It does not measure mastery.