So, a Jagged array is basically a array of arrays. This means that the elements in a jagged array are single-dimensional or multi-dimensional arrays. You initiate a jagged array by doing:
type[ ][ ] nameOfArray = new int[#][ ];
-or in the case of the elements being multidemnsional arrays-
type[ ][ , ] nameOfArray = new int[#][ , ];
The number is optional(# can be a symbol for number). It’s just telling the compiler how many elements are in the jagged array, and c# doesn’t require you to tell it that when you initialize the array.
You put elements into the array by:
nameOfArray[indexNumberOfElement] = new type[#];
-or multi dimensional-
nameOfArray[indexNumberOfElement] = new type[#,#];
-or with the arrays being specified-
nameOfArray[indexNumberOfElement] = new type[#] { Var1, Var2,etc};
You can also declare and initialize at the same time:
type[ ][ , ] nameOfArray = new int[#][ , ]
{
new type[#,#] { {Var1,Var2,etc} ,{Var3,Var4,etc}, etc},
new type[#,#]{ {Var1,Var2,etc} ,{Var3,Var4,etc}, etc},
etc
}
For the jagged arrays the number of elements in the array elements can vary, as in a array of 4 elements and a array of 20 elements can be in the same jagged array. You can also leave out the “new int[#][ , ]” and it will still compile.
2 thoughts on “C# Jagged Arrays”
Comments are closed.