Groups | Blog | Home
all groups > dotnet clr > march 2008 >

dotnet clr : Array.CreateInstance failure


Edgile
3/6/2008 8:58:02 AM
Hello,

Bellow is a little except that creates a static array dynamically. However
it creates
a two dimensional one instead of a single dimensional. Why????

public static void Main(string[] args)
{
int[] intArray = new int[]{2,3};
Type type = intArray.GetType();
Array array = Array.CreateInstance(type, 0);
// array is a two dimensional array. Why?
intArray = (int[]) array; // Throws InvalidCastException, as expected
Console.WriteLine();
}
Jon Skeet [C# MVP]
3/6/2008 5:35:13 PM
[quoted text, click to view]

Because you've said you want an array where each element is of type
int[]. If you want the overall array to be int[], use
Array.CreateInstance(typeof(int), 0)

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Ben Voigt [C++ MVP]
3/6/2008 6:16:15 PM
[quoted text, click to view]

It isn't a two dimensional array. You can test that

int[,] array2d = (int[,]) array; // InvalidCastException

and

array.Rank will be 1, not 2.

In fact it is a one dimensional array where the element type is
intArray.GetType() as you requested, that is each element is an array.

This array-of-arrays is sometimes called a jagged array.

If you want an array of the same type as the first array, use
intArray.GetType().MemberType

Edgile
3/17/2008 2:45:02 AM
Thanx for the answers to both Ben and Jon, you were absolutely correct.

[quoted text, click to view]
AddThis Social Bookmark Button