Failure is inevitable


What's wrong with this code?

I just learned something new about C#.  You can cast an array of any type to an array of objects, like so:

   1: object[] oa = new string[] {"abc", "def", "ghi"};
   3: //Will write 'abc'
   4: Console.WriteLine(oa[0]);

No compiler warnings, no runtime errors, everything is happy.  You can then modify the array, like so:

   1: oa[0] = "xyz";
   3: //Will write 'xyz'
   4: Console.WriteLine(oa[0]);

Again, no errors anywhere, things just work, and you (hopefully) already knew that.

But what about this:

   1: oa[0] = 5;
   3: //Uhh...
   4: Console.WriteLine(oa[0]);

What's going to happen there?  No compiler warnings, but runtime EXPLOSION. I have never encountered an ArrayTypeMismatchException in practice, but there it is. Neat!  Thanks, Channel 9!

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications. He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight, where he publishes courses on everything from web applications to testing!

blog comments powered by Disqus