Covariance and Contravariance

Bharat Mane
2 min readNov 14, 2021

The Idea

Covariance and contravariance come from mathematics. It is a measure of how changes in one variable are associated with changes in a second variable. It measures the degree to which two variables are linearly associated. In other words, it describes what happens when a change occurs. If the result goes in the same direction as the change, it is covariant, otherwise, it is contravariant. (Original Source)

Covariance: Presever assignment compatibility
Contravariance: Reverses assignment compatibility
Covariance and contravariance enable implicit reference conversion for array, delegate, and generic types.

In C# there are three areas where it plays an important role

  • Delegate Types
  • Array Types
  • Generic Type Arguments

Covariance with Delegates

Contravariance with Delegates

Covariance with arrays

Covariance with Generics

Contravariance with Generics

Conclusion

Covariance and contravariance are borrowed from mathematics and are relative to Subtyping, more specifically to object hierarchies and substitution. Covariance allows us to pass a derived type where a base type is expected. On the other hand, contravariance allows a method with the parameter of a base class to be assigned to a delegate that expects the parameter of a derived class.

References:

Thanks to Greg Kalapos for his video on YouTube

--

--

Bharat Mane

I am a photographer, a runner, a cyclist, and an aspiring storyteller who happened to fall in love with coding and have the desire to be proud of what I do.