Variance: Covariance and Contravariance

Covariance and Contravariance are advanced concepts and I will explain them starting from the concept of type inheritance.

One of the pillars of object oriented programming languages is type inheritance. For example we could have a base class named Fruit and a derived class named Apple.

class Fruit
{
    public override string ToString()
    {
        return "Fruit";
    }
}

class Apple : Fruit
{
    public override string ToString()
    {
        return "Apple";
    }
}

Wherever a Fruit instance is required, an Apple instance will do just fine. Implicit conversion exists from derived type to base type:

Fruit fruit = new Apple();

In order to covert from a base type instance to a derived type instance an explicit cast or explicit reference conversion is required.

Fruit fruit = new Apple();
Apple apple1 = (Apple)fruit;
Apple apple2 = fruit as Applel

The Variance (Covariance and Contravariance) refers to how generic types can be converted from one to another based on the relation between their type parameters.

CovarianceX is covariant if X<Apple> is convertible (via an implicit reference conversion) to X<Fruit>.

ContravarianceX is contravariant if X<Fruit> is convertible  (via an implicit reference conversion) to X<Apple>.

Example:

using System;

class Program
{
    static void Main()
    {
        // Covariance Func<out TResult>
        Func<Apple> funcApple = FuncApple;
        Func<Fruit> funcFruit = funcApple;

        // Contravariance Action<in T>
        Action<Fruit> actionFruit = ActionFruit;
        Action<Apple> actionApple = actionFruit;
    }

    static Apple FuncApple() { return new Apple(); }

    static void ActionFruit(Fruit fruit) { Console.WriteLine(fruit); }
}

class Fruit
{
    public override string ToString()
    {
        return "Fruit";
    }
}

class Apple : Fruit
{
    public override string ToString()
    {
        return "Apple";
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s