Variance and interface contracts
Variance and interface contracts
Variance describes a permitted conversion between constructed generic interfaces or delegates whose type arguments have an appropriate reference conversion. Covariance (out) lets a producer of a more specific reference type be used as a producer of a less specific one. Contravariance (in) lets a consumer of a less specific reference type be used where a consumer of a more specific type is needed. An invariant parameter supports neither substitution merely because its type arguments are related.
Use the producer/consumer mental model for ordinary parameter and result positions. The actual compiler rules also account for nested variant generic types. These modifiers on generic type parameters are not the ref, in or out argument-passing modifiers. Classes and structs cannot declare variant type parameters. Variance conversions require reference conversions, not boxing or numeric conversions.
using System;using System.Collections.Generic;var books = new List<Book> { new Book("Atlas") };IEnumerable<Publication> publications = books;foreach (Publication p in publications) Console.WriteLine(p.Title);books.Add(new Book("Maps"));foreach (Publication p in publications) Console.WriteLine(p.Title);record Publication(string Title);record Book(string Title) : Publication(Title);IEnumerable<out T> supports the conversion because a Book can be read as a Publication. The interface refers to the same source, not a copied list or immutable snapshot. The later addition occurs between enumerations, not during one.
Expected output (reasoned, not executed):
AtlasAtlasMapsAccept a general consumer as a specific consumer
using System;IReceiver<Publication> receiver = new TitleReceiver();IReceiver<Book> bookReceiver = receiver;bookReceiver.Receive(new Book("Atlas"));interface IReceiver<in T> { void Receive(T value); }class TitleReceiver : IReceiver<Publication>{ public void Receive(Publication value) => Console.WriteLine(value.Title);}record Publication(string Title);record Book(string Title) : Publication(Title);A receiver that accepts any Publication can also accept a Book. The in modifier permits the direction from the general consumer to the specific consumer interface.
Expected output (reasoned, not executed):
AtlasContrast covariance with invariant mutable storage
using System;using System.Collections.Generic;var books = new List<Book> { new Book("Atlas") };IReadOnlyList<Publication> readable = books;Console.WriteLine(readable[0].Title);object candidate = books;Console.WriteLine(candidate is List<Publication>);Console.WriteLine(candidate is IEnumerable<Publication>);record Publication(string Title);record Book(string Title) : Publication(Title);The list cannot be converted to List<Publication>; if that were possible, callers could insert a Publication that is not a Book. Its covariant read interfaces do support base-type access. Read-only access is not a promise that another holder cannot mutate the source.
Expected output (reasoned, not executed):
AtlasFalseTrueCommon mistakes and edge cases
IEnumerable<int> cannot become IEnumerable<object> through covariance: converting an individual int to object would require boxing. A mutable List<Book> remains invariant even though it implements variant interfaces. Prefer the narrowest interface needed by callers, not unsafe casts. Delegates (callable values) can also declare variance, for example Func<out TResult> and Action<in T>; detailed delegate usage is deferred to chapter 17. The negative diagnostic fixture shows the invalid list assignment directly.
Practice and next steps
Create classes Animal and Dog : Animal. Build a List<Dog> with one Dog. Read it through IEnumerable<Animal>, then explain why List<Animal> animals = dogs; fails. Define IHandler<in T> with void Handle(T value) and show the safe conversion from IHandler<Animal> to IHandler<Dog>.
Next: Choosing collection interfaces.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variance and interface contracts — knowledge check
Apply the lesson concepts to the following scenarios.
Which conversion is covariant?
Which modifier declares a contravariant generic interface parameter?
Why is List<Book> not a List<Publication>?
Does a conversion to IReadOnlyList<Publication> copy the list?
Why does IEnumerable<int> not convert to IEnumerable<object> by variance?