Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 447
Candy Chiu Avatar asked Aug 22 '12 19:08

Candy Chiu


3 Answers

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[*]
like image 144
Marc Gravell Avatar answered Oct 22 '22 11:10

Marc Gravell


I can't find the actual code to verify, but experimenting that syntax seems to indicate a one-dimensional array with a non-zero base.

Here's my results:

0-Based 1-D Array :        "System.Int32[]"
Non-0-based 1-D Array:     "System.Int32[*]"
0-based 2-D Array :        "System.Int32[,]"
Non-0-based 2-D Array :    "System.Int32[,]"
like image 3
D Stanley Avatar answered Oct 22 '22 13:10

D Stanley


If all you need is one-dimensional array, than this should do the trick

Array.CreateInstance(typeof(int), length)

When you specify lowerBound, then returning type if quite different

var simpleArrayType = typeof(int[]);

var arrayType = Array.CreateInstance(typeof(int), 10).GetType();
var arrayWithLowerSpecifiedType = Array.CreateInstance(typeof(int), 10, 5).GetType();

Console.WriteLine ( arrayType == simpleArrayType ); //True
Console.WriteLine ( arrayWithLowerSpecifiedType == simpleArrayType ); //False
like image 2
Ilya Ivanov Avatar answered Oct 22 '22 12:10

Ilya Ivanov