Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariance and contravariance

Tags:

c#

May be my question is dumb but here it is.

Is Covariance and contravariance only applicables for delegates in c#?

Can we have Covariance and contravariance in normal class hierarchies?

like image 330
TalentTuner Avatar asked Jan 30 '26 06:01

TalentTuner


1 Answers

Is Covariance and contravariance only applicables for delegates in c#?

Not quite; the language-level variance can also apply to interfaces, for example IEnumerable<out T> (likewise in is fine too).

I should also note that arrays of reference-types are also covariant:

string[] orig = {"abc","def"};
object[] sameArray = orig;

Can we have Covariance and contravariance in normal class hierarchies?

No; it does not apply to classes / structs (although you can of course implement a covariant interface, and coerce to that interface).

like image 88
Marc Gravell Avatar answered Jan 31 '26 20:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!