Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of good, real-life use-cases for covariance and contravariance in C# 4.0?

Before C# 4.0 came out, I was quite excited about covariance and contravariance. It pandered to my fondness for theoretical correctness!

However, now that it’s out, and I’m back to writing normal, everyday, boring code, I’m starting to wonder: did I ever use it yet? And I notice that I haven’t used it consciously. None of the interfaces or delegates I have defined since have benefited from it.

There is only one single case in which I later discovered I unwittingly used covariance, but it’s very subtle and I could as well have not noticed it. Imagine X is a base-class and Y is a descendent of it:

if (enumerableOfYs.Contains(variableOfTypeX))

Are there any interesting or exciting examples where any of you guys have used covariance or contravariance in a real-life, non-contrived use-case and it has really saved the day by being spectacularly “correct”?

like image 359
Timwi Avatar asked Aug 27 '10 05:08

Timwi


People also ask

What is the use of covariance and contravariance?

Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.

Why is contravariance useful?

This is useful whenever you want to access some common method or property of a collection which can contain items of one or more types derived from a base class. For example, you might have a hierarchy representing different categories of stock for a supermarket.

Can you be declared as Contravariant?

A type can be declared contravariant in a generic interface or delegate only if it defines the type of a method's parameters and not of a method's return type. In , ref , and out parameters must be invariant, meaning they are neither covariant nor contravariant.

What does covariance mean in programming?

Variance refers to how subtyping between more complex types relates to subtyping between their components.


1 Answers

The only "real world" use of variance that I've run into in my actual writing-programs-for-customers (as opposed to writing compiler test cases or articles or whatever) is I now can pass an IEnumerable<TypeParameterDefinedInSource> to a method that expects an IEnumerable<TypeSymbol> when I write code analysis tools in C#.

It's really not a "save the day" sort of feature. It's more of a "it works the way I expect it to" feature.

like image 181
Eric Lippert Avatar answered Sep 19 '22 10:09

Eric Lippert