C#: Array.CreateInstance: Unable to cast object of type [*] to type []

c#

Solution

Yes, this is a gotcha!

There's a difference between a vector and a 1-dimensional array. An `int[]` is a vector. A vector (like an `int[]`) must be 0-based. Otherwise, you have to call it `Array`. For example:

// and yes, this is doing it the hard way, to show a point...
int[] arr1 = (int[]) Array.CreateInstance(typeof(int), length);

or (noting that this is still zero-based):

int[] arr2 = (int[]) Array.CreateInstance(typeof (int),
      new int[] {length}, new int[] {0});

If your array can't be 0-based, then sorry: you have to use `Array`, not `int[]`:

Array arr3 = Array.CreateInstance(typeof(int),
      new int[] { length }, new int[] { lower });

To make it even more confusing, there's a difference between:

typeof(int).MakeArrayType() // a vector, aka int[]
typeof(int).MakeArrayType(1) // a 1-d array, **not** a vector, aka int[*]

Problem

I want to create a non zero lower bound one dimensional array in c# by calling ``` Array.CreateInstance(typeof(int), new int[] { length }, new int[] { lower }); ``` The type of the returned array is not int[], but int[*]. Can anyone elaborate on what does this mean? I want to be able to return this array to the caller, for example, ``` int[] GetArray() { ... } ``` Thanks.

Original source