Daily Knowledge Drop
A jagged array
is an array of arrays, where each internal array can be of varying length.
Array
A quick recap on a traditional one dimensional array:
var array = new int[10];
int[] array1 = new int[10];
The array size is defined when the variable is instantiated - this array is defined to hold up to 10 int's.
Multi-dimensional array
A multiple dimensional is declared and instantiated the same way as a one-dimensional array:
// declare a two dimensional array
int[,] multiArray = new int[10,10];
// a three dimensional array
int[,,] multiArray1 = new int[10, 10, 10];
With multiple directional arrays, the size of the dimension is fixed. In the above two-dimensional array for example, a 10x10 array is defined - it can be thought of a grid with 10 columns and 10 rows. The important aspect is that each row will always
have 10 columns at most.
Jagged array
A jagged array
is an array of arrays, where the internal array is of varying length.
There is a subtle difference when declaring a jagged array
vs declaring a multiple dimensional array:
// Jagged array
int[][] jaggedArray1 = new int[10][];
// For comparison - multi directional array
int[,] multiArray = new int[10,10]
The jagged array jaggedArray1, has 10 rows, but each row has varying column length - a second size is not specified when declaring the array. As it stands now, each row is null by default - the array in each row needs to be initialized:
jaggedArray1[0] = new int[5];
jaggedArray1[1] = new int[3];
jaggedArray1[2] = new int[1];
The first 3 rows are being initialized to each have a different number of items. We have an array of arrays, with each internal array being of different sizes.
Notes
This is not functionality I've personally ever had to use - but I am sure it definitely does have its practical uses cases. Just being aware the functionality exists can help make better, more informed design choices going forward.
References
Daily Drop 191: 31-10-2022
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.