Initializing jagged arrays

AndreyAkinshin picture AndreyAkinshin · Nov 15, 2009 · Viewed 20.5k times · Source

I want to create array 10 * 10 * 10 in C# like int[][][] (not int[,,]).

I can write code:

int[][][] count = new int[10][][];

for (int i = 0; i < 10; i++) 
{
    count[i] = new int[10][];

    for (int j = 0; j < 10; j++)
        count[i][j] = new int[10];
}

but I am looking for a more beautiful way for it. May be something like that:

int[][][] count = new int[10][10][10];

Answer

dtb picture dtb · Nov 15, 2009
int[][][] my3DArray = CreateJaggedArray<int[][][]>(1, 2, 3);

using

static T CreateJaggedArray<T>(params int[] lengths)
{
    return (T)InitializeJaggedArray(typeof(T).GetElementType(), 0, lengths);
}

static object InitializeJaggedArray(Type type, int index, int[] lengths)
{
    Array array = Array.CreateInstance(type, lengths[index]);
    Type elementType = type.GetElementType();

    if (elementType != null)
    {
        for (int i = 0; i < lengths[index]; i++)
        {
            array.SetValue(
                InitializeJaggedArray(elementType, index + 1, lengths), i);
        }
    }

    return array;
}