O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required