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.
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);
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