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.
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[*]
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[,]"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With