Array casting weirdness


The .NET runtime is type-safe. Sometimes compilers perform magic for us, that make us think that one type is substitutable for another. VB.NET is such an example. The VB compiler will cast and convert for you automatically if possible. You can turn this behavior off by specifying Option Strict On.


A couple of weeks ago I noticed a bug in DotNetMock 0.7.6. It showed me something that had me puzzled. Take this code fragment:


public class Base { }
public class Derived : Base
{ }

private
void CastArray()
{
  Derived[] derivedArray = new Derived
[10];
  for (int i = 0; i < 10; i++) derivedArray[i] = new Derived
();
  Base[] baseArray = (Base
[])derivedArray;
  object[] objectArray = (object[])derivedArray;
  }
}


Guess what? The casts work. To the best of my knowledge object[], Base[] and Derived[] are different types and one cannot be cast into the other. The individual elements can be cast into each other, sure. But not the array references themselves. Is there some C# compiler magic involved? Are arrays not treated the way I think. To make it worse, when you do the same with a cast between a value type array and an object[], the cast fails (which was the bug in DotNetMock). I assume the obligatory boxing of the value types has something to do with it.


I’m interested in your explanation or opinion in this. Comments below, please.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s