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”?
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.
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.
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.
Variance refers to how subtyping between more complex types relates to subtyping between their components.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With