Mar 4 2009

What's wrong with this code?

Category: What NOT To DoMatt @ 04:05

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"};
   2:  
   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";
   2:  
   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;
   2:  
   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!

Tags:

blog comments powered by Disqus