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”?