Suppose we have my usual hierarchy of types,
Giraffe, etc, with the obvious type relationships. An
IEqualityComparer<T> is contravariant in its type parameter; if we have a device which can compare two
Animals for equality then it can compare two
Giraffes for equality as well. So why does this code fail to compile?
IEqualityComparer<Animal> animalComparer = whatever;
IEnumerable<Giraffe> giraffes = whatever;
IEnumerable<Giraffe> distinct = giraffes.Distinct(animalComparer);
This illustrates a subtle and slightly unfortunate design choice in the method type inference algorithm, which of course was designed long before covariance and contravariance were added to the language.
Here’s a question I got from a coworker recently:
It is obviously important that the C# compiler not go into infinite loops. How do we ensure that the method type inference algorithm terminates?
The answer is quite straightforward actually, but if you are not familiar with method type inference then this article is going to make no sense. You might want to watch this video if you need a refresher. Continue reading
(Note: not to be confused with Inheritance and Representation.)
I get a fair number of questions about the C# cast operator. The most frequent question I get is:
short sss = 123;
object ooo = sss; // Box the short.
int iii = (int) sss; // Perfectly legal.
int jjj = (int) (short) ooo; // Perfectly legal
int kkk = (int) ooo; // Invalid cast exception?! Why?
Why? Because a boxed T can only be unboxed to T (or
Nullable<T>.) Once it is unboxed, it’s just a value that can be cast as usual, so the double cast works just fine.