views:

505

answers:

4

Hi,

How do you declare a "deep" array in C#?

I would like to have a int array like: [ 1, 4, 5, 6, [3, 5, 6, 7, 9], 1, 4, 234, 2, 1,2,4,6,67, [1,2,4,44,56,7] ]

I've done this before, but can't remember the right syntax. But it was something a like what is written below: Int32[] MyDeepArray = new Int32[] = {3, 2, 1, 5, {1, 3, 4, 5}, 1, 4, 5};

And how do I iterate it correctly.. How do I check that an array is an array?

Thanks!

+6  A: 

I believe the term you're looking for is a jagged array.

It can be done like this:

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

And you can iterate through them like this:

for(int i = 0; i < jaggedArray2.Length; i++)
    for(int j = 0; j < jaggedArray2[i].Length; j++)
    {
        //do something here.
    }
Joseph
Or just do a nested foreach.
Steven Sudit
@Steven Yeah, I was using traditional for so he could better understand the jagged nature of the arrays..
Joseph
+1  A: 

Int32[][] will allow you to declare a 2-dimensional array where the dimensions do not all have to be the same. So, for example, you could have the following:

[
[2,3,4,5]
[5]
[1,2,3,4,5,6,7,8]
[3,5]
[4]
]

The alternative is Int32[,] where the dimensions always have to be the same.

I'm not sure what you mean by "how do I check that an array is an array."

JasCav
+1  A: 

Here's some good documentation on using C# arrays. There's some information about iteration using foreach and other methods too.

http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx

CodeFusionMobile
A: 

As for "how do I check that an array is an array": C# is strongly typed. anything that is declared as an array must be an array. what you are looking for is an array, not of integers, but of arrays of integers. therefore, every item in your outer array is a strongly typed array of integers. it's not integers and arrays of integers all mixed up. the closest thing you'll get is int-arrays and int-arrays-containing-only-one-int all mixed up. given that, you can always iterate through them, regardless, because they are all arrays, you can treat them all like arrays, and those that only contain one item will only step into the iteration once.

if you want to explicitly check, because you're treating the int-arrays-with-only-one-int differently, then you can check for their .Length value.

David Hedlund