Difference between Covariance & Contravariance

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

It’s probably easiest to give examples – that’s certainly how I remember them.

 (covariant return types/contravariant parameter types)

Covariance

Canonical examples: IEnumerable<out T>Func<out T>

You can convert from IEnumerable<string> to IEnumerable<object>, or Func<string> to Func<object>. Values only come out from these objects.

It works because if you’re only taking values out of the API, and it’s going to return something specific (like string), you can treat that returned value as a more general type (like object).

Contravariance

Canonical examples: IComparer<in T>Action<in T>

You can convert from IComparer<object> to IComparer<string>, or Action<object> to Action<string>; values only go into these objects.

This time it works because if the API is expecting something general (like object) you can give it something more specific (like string).

  • Covariance => Object=string;
  • Contravariance=> string=Object;

 


Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.