Covariance and Contravariance on the same type argument
Posted
by
William Edmondson
on Stack Overflow
See other posts from Stack Overflow
or by William Edmondson
Published on 2010-12-24T20:22:52Z
Indexed on
2010/12/25
1:54 UTC
Read the original article
Hit count: 559
The C# spec states that an argument type cannot be both covariant and contravariant at the same time.
This is apparent when creating a covariant or contravariant interface you decorate your type parameters with "out" or "in" respectively. There is not option that allows both at the same time ("outin").
Is this limitation simply a language specific constraint or are there deeper, more fundamental reasons based in category theory that would make you not want your type to be both covariant and contravariant?
Edit:
My understanding was that arrays were actually both covariant and contravariant.
public class Pet{}
public class Cat : Pet{}
public class Siamese : Cat{}
Cat[] cats = new Cat[10];
Pet[] pets = new Pet[10];
Siamese[] siameseCats = new Siamese[10];
//Cat array is covariant
pets = cats;
//Cat array is also contravariant since it accepts conversions from wider types
cats = siameseCats;
© Stack Overflow or respective owner