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.