0
votes

Covariance and contravariance provides implicit reference conversion for Arrays, Delegates and Generic parameter types.

IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings;

Action<object> actObject = SetObject;
Action<string> actString = actObject;

Does normal object base type derived type conversion come under Covariance and contravariance as stated below ?

ChildClass childobj=new ChildClass;
BaseClass baseobj=childobj;

BaseClass baseobj=new BaseClass;
ChildClass childobj= (BaseClass) baseobj;

If so how runtime handles it and If not why?

1
Example 3 and 4 are not covariance and contravariance. They are just reference conversion. Example 4 won't compile. - Sriram Sakthivel

1 Answers

0
votes

Covariance and Contravariance only applies to parametric polymorphism, eg. when one type has other type as parameter. That is because some use cases might compile even tought they are not typed soundly. For example like this.

Your second example is just simple data polymorphism for which there is no need to apply covariance and contravariance, because those use cases don't apply.