0
0
C Sharp (C#)programming~5 mins

Covariance with out keyword in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Covariance lets you use a more specific type than originally expected when working with interfaces or delegates. The out keyword helps make this safe and easy.

When you want to return a more specific type from a method than the interface says.
When you have a collection of a derived type but want to treat it as a collection of a base type.
When you want to assign an interface of a more derived type to a variable of a less derived type.
When working with read-only data sources where you only get values out.
Syntax
C Sharp (C#)
interface IEnumerable<out T> {
    T GetItem();
}

The out keyword marks the generic type parameter as covariant.

Covariance works only for output (return) types, not input (method parameters).

Examples
You can assign a list of strings to a variable expecting objects because T is covariant.
C Sharp (C#)
IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings; // Allowed because of covariance
The out keyword allows IFactory<Derived> to be used where IFactory<Base> is expected.
C Sharp (C#)
interface IFactory<out T> {
    T Create();
}
Sample Program

This program shows how a list of Dog can be assigned to a variable of IEnumerable<Animal> because of covariance with the out keyword.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Animal {
    public virtual string Speak() => "Animal sound";
}

class Dog : Animal {
    public override string Speak() => "Woof";
}

class Program {
    static void Main() {
        IEnumerable<Dog> dogs = new List<Dog> { new Dog() };
        IEnumerable<Animal> animals = dogs; // Covariance with out keyword

        foreach (var animal in animals) {
            Console.WriteLine(animal.Speak());
        }
    }
}
OutputSuccess
Important Notes

Covariance only works with interfaces and delegates that have out on their generic type parameters.

You cannot use covariant types as method input parameters.

This helps make your code more flexible and type-safe when working with inheritance.

Summary

Use out to make generic type parameters covariant.

Covariance allows assigning more derived types to less derived types safely.

It works only for output positions like return types, not input parameters.