← Back to C# Course | Chapter 11: Generics | Lesson 5 of 6

Covariance and Contravariance

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

markup
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>
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.