Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically created jagged rectangular array

Tags:

arrays

c#

.net

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.

like image 407
GaGar1n Avatar asked Feb 03 '23 05:02

GaGar1n


1 Answers

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);
like image 80
Henk Holterman Avatar answered Feb 07 '23 12:02

Henk Holterman