Reputation: 1040
In my project I have a lot of code like this:
int[][] a = new int[firstDimension][];
for (int i=0; i<firstDimension; i++)
{
a[i] = new int[secondDimension];
}
Types of elements are different.
Is there any way of writing a method like
createArray(typeof(int), firstDimension, secondDimension);
and getting new int[firstDimension][secondDimension]
?
Once again, type of elements is known only at runtime.
Upvotes: 9
Views: 6961
Reputation: 273494
Generics should do the trick:
static T[][] CreateArray<T>(int rows, int cols)
{
T[][] array = new T[rows][];
for (int i = 0; i < array.GetLength(0); i++)
array[i] = new T[cols];
return array;
}
You do have to specify the type when calling this:
char[][] data = CreateArray<char>(10, 20);
Upvotes: 11
Reputation: 11495
If:
You can use Array.CreateInstance something like:
static Array CreateArray (Type t, int rows, int cols)
{
Array arr = Array.CreateInstance (typeof(Array), rows);
for (int i = 0; i < rows; rows++) {
arr.SetValue (Array.CreateInstance(t, cols), i);
}
return arr;
}
But are you sure you need this to by dynamic type at runtime?
Upvotes: 1
Reputation: 19601
As mOsa mentioned, if you want rectangular jagged array, then you are better off using a multi-dimensional array.
int[,] array = new int[dimension, dimension2];
will generate a rectangular array.
The reason to use a jagged array, is if you want to create an array with different secondary dimensions. A jagged array is really an array of arrays, where as a multi-dimensional array is a slightly different beast.
Upvotes: -1
Reputation: 10940
Well you can do this:
int[,] array = new int[4,2];
What you get is called a multidimensional array (4x2). Here is a nice article about multidimensional arrays.
The term jagged array usually refers to arrays, that have different second dimensions. For example take:
int[][] jagged = new int[2][];
jagged[0] = new int[5]; // 5 elements
jagged[1] = new int[1]; // 1 element
so this is not a 2x5 array, but a jagged array..
Upvotes: 1