Safety Guarantees

Co- and contravariance are means to add flexibility to the type system, ideally while making sure type safety cannot be violated. The flexibility part is clear: being able to treat an array of apples as an array of coconuts is more powerful than not being able to do so. But why is this example of array covariance unsafe? The true answer lies in the writable characteristic of an array:

// We're putting a Coconut, which is a Fruit, in a Fruit-array. This is// actually not fine if the underlying array has a more specific element type.fruits[2] = new Coconut();

If the fruits variable is referencing an array with an element type that’s more specific than Fruit, the preceding code is not fine. The reason ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.