0

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?

Euphoric
  • 12,645
  • 1
  • 30
  • 44
Anoob K A
  • 59
  • 8

1 Answers1

0

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.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • Thanks for your quick response.In C# arrays where the element type is reference type are covariant. Eg: Animal[] animals=new Mammal[10]; For arrays it does not applies to parametric polymorphism and that also holds data. Then how does it come under Covariance and Contravariance ? – Anoob K A Aug 01 '14 at 06:46
  • 1
    @AnoobAliyar You need to consider that also as parametric polymorphism. Assume `Animal[]` as `Array`, then everything is clear. – Sriram Sakthivel Aug 01 '14 at 06:51
  • @AnoobAliyar Exactly what Sriram says. Just because there is different syntax doesn't mean the types are different. – Euphoric Aug 01 '14 at 07:10
  • Are you saying like the array will be represented internally like Array ? Please suggest some useful links for data polymorphism if you have any. – Anoob K A Aug 01 '14 at 08:31