TalentTuner
TalentTuner

Reputation: 17556

Covariance and contravariance

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?

Upvotes: 3

Views: 465

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

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).

Upvotes: 8

Related Questions