Monday, 4 January 2010

Covariance, Contravariance, Invariance

Generally if an operator changes the type in some kind, it’s called variant.

If it retains the type (the type is fix), then it’s called invariant.

If an operator orders types in the way from general to more specific for any type, then it is called to be covariant.

If it orders types reversely from specific to more general, then it’s contravariant.
public class Vehicle
{

}

public class Car: Vehicle
{

}

public class Honda: Car
{

}





1. Covariance:

Covariance is the ability to assign an expression of a more specific type to a variable of a less specific type.

Methods in C# are ‘covariant’ in their return types

   // Valid since Honda inherits from Car
public Car GetCar1()
{

return new Honda();
}

// Valid
public Car GetCar2()
{

return new Car();
}

// Compile-time error
public Car GetCar3()
{

return new Vehicle();
}

Referenced type arrays are 'covariant'

2. Contravariance

Method arguments in C# are 'contravariant'

3. Invariance

'int[] arr;' is invariant.

Generic delegate types are always invariant in C# 3.0.

To be continued…

No comments: