Sometimes it’s not the developer’s fault. Instead, perhaps the runtime or framework designers are to blame. Luckily, this doesn’t happen very often, but ArrayTypeMismatchException shows that it does happen.

The introduction of covariant arrays, as discussed in Chapter 15, “Generic Types and Methods,” was an unfortunate choice made in the early .NET 1.0 days (for very good reasons back then). This exception catches a mishap in using covariant arrays at runtime that should have instead been caught at compile time:

int[] nums = new[] { 1, 2, 3 };object[] numsInDisguise = nums;numsInDisguise[1] = "two"; // Ow!

To see why this is a problem and how this issue is avoided for generic types, see Chapter 15. Luckily, arrays aren’t ...

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.