Does C# support nested jagged arrays?

1900 views c#
-1

I would like to know if C# has a way of defining strongly-typed nested jagged arrays without using object[]. something like: var nested = new {1, 2, {3, {4, 5}, 6}, 7};

I would like to have a nested array of int.

Consider this array below: [[1, 2, [3]], 4, [5], [[[6]]]]

This is how I've done it:

var myNestedJagged = new object[]
{
    new object[]
    {
        1, 2, new object[] {3}
    },
    4,
    new object[] {5},
    new object[] {new object[] {new object[] {6}}}
};

answered question

The only way I think you could start to strongly type this Jagged Array is by creating classes and using generics withinin those classes to represent your Jagged Array

Yeah, I thought so. I would like to know if there's a way of doing it using something like new int[][] { }

This is so ridiculously easy with javascript, but C# seems to have its limitations with such dynamic array

No I do not think you could express a jagged array like that C#, pros and cons to every programming language

Hate to nitpick, but this is not a jagged array. A jagged array is an array that contains arrays of different lengths, such as { { 1 }, { 1, 2, 3, 4}, { 1, 2 }, { 1, 2, 3, 4, 5, 6, 7 } }.

1 Answer

8

Yes. Straight from the article Jagged Arrays from microsoft docs (go figure):

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes.

int[][] jaggedArray2 = new int[][] 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};
int[][] jaggedArray3 = 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

posted this

Have an answer?

JD

Please login first before posting an answer.