C# the language, right from the very beginning is always supported covariance and contravariance but in most simple scenario, now in C# 4.0 we have full support of covariance and contravariance in all circumstances, generic interface and generic delegates, other C# types already support from first version of C#. These two terms sounds like technically scary as we will see they are incredibly simple concepts and once we will finish this, you will agree that they are not scary.
We can say C# 4.0 has not introduced new feature but what it has done is fixed a bug, it’s basically broad in two line, the way in particular generic interface and generic delegate how they work in polymorphism.
Let’s create a class Car and derived two other classes Sedan and Coupe from this class as follows:
public class Car
{
}
public class Sedan:Car
{
}
public class Coupe:Car
{
}
Now try to create object of Car and initialize with object of Sedan or Coupe
Car objcar = new Sedan();// valid statement objcar = new Coupe(); valid statement
As you can see here we used dynamic polymorphism, till now everything is ok, a Car can be Sedan or Coupe, what about a group of Sedan? Can a group of Sedan or Coupe be a group of Car? Like this
IEnumerable<Car> cars = new List<Sedan>(); cars = new List<Coupe>();
Theoretically it should be, because if sedan is a car then a group of sedan should be a group of car but it is not true, if you will try this with C# 3.5 it will give error because C# 3.5 does not support covariance/contravariance with generic interface and generic delegate, here is the error:
Cannot implicitly convert type 'System.Collections.Generic.List< Sedan>' to 'System.Collections.Generic.IEnumerable< Car>'. An explicit conversion exists (are you missing a cast?)
Open project property and select Application tab and change the target framework to 4.0 and now the same code will work because covariance & contravariance with generic interface and generic delegate is supported by framework 4.0.
No comments:
Post a Comment