Search code examples
c#arrays.net.net-coreclr

Why non zero based arrays with 1 and 2 rank have different types?


.Net has special internal type for non zero based array.

C# language hasn't syntax for this type, so you can't cast to this type.

But 2d non zero based array has normal array type.

I wonder why only 1d array has special type?

var array1 = (int[]) Array.CreateInstance( typeof( int ), new[] { 6 }, new[] { -1 } ); // System.InvalidCastException : Unable to cast object of type 'System.Int32[*]' to type 'System.Int32[]'
var array2 = (int[,]) Array.CreateInstance( typeof( int ), new[] { 6, 6 }, new[] { -1, -1 } ); // it works

Solution

  • A 0-based, 1-dimensional array is special. It's a "vector array". They are heavily optimized by the CLR.

    Any array that is not 0-based or not 1-dimensional is not a vector array.
    Therefore, an int[,] is not a vector array so the 2nd cast works.
    int[*] and int[] are really different types.