0
votes

I've been looking into that and there is something I can't quite grasp. In few words COvariance is when you need BASE class, but use DERIVED instead, and CONTRAvariance is when you need DERIVED class but use BASE instead, right?

I've been watching this video : https://www.youtube.com/watch?v=3MQDrKbzvqU where the example is given:

//COvariance with object
Mammal m = new Zebra(); 

//CONTRAvariance with object
Zebra z = new Zebra();
ContravariantMethod(z);

static void ContravariantMethod(Mammal m) { m.Display(); }

in ContravariantMethod base is needed, but I provide derived. So how is that contravariant at all? I come to the conclusion the video is misleeding.

And what about in and out keywords in covariant/contravariant delegates? While it makes sense not to be allowed to return BASE instead of DERIVED, why it is a problem to return DERIVED instead of BASE, and why the compiler can't implicitly cast it if it's such a problem, as a matter of fact?

And when I try my own contravariance it's expectedly, giving me an error:

mmmmm(new Mammal());
static void mmmmm(Zebra z) { z.Display(); }
1
Co and contravariance only make sense with generic methods. Since ContravariantMethod is not generic, it is not covariant. - Lee
In the video the method accepts IEnumerable<Mammal> and the co/contravariance is in this generic type not in the method itself. - Stilgar
So that video really IS misleading after all? No, this is the Interface case, I mean the 1st and most simple one. - Gogo
@Lee (and upvoters) co and contravariance also apply to delegates and have done so since before generics existed. - Rawling
@Rawling - Ok it's more precise to talk about variance applying to functors rather than generic types in particular, although explicit variance annotations only apply to generic parameters. Variance of delegates\methods only applies when using them as values, not when applying them as in this case. - Lee

1 Answers

1
votes

Covariance and Contravarience works with generics and delegates. So your Mammal methods are neither Covariance nor Contravarience. It's just polymorphism. Covariance and Contravarience is closely related to the out and in generic modifiers. To learn more about generic modifiers, see the links below:

out

in

Hope the links helped!