Jagged Arrays

As you learned earlier, arrays have a type constructor nature, meaning any existing type can be used to create another array type (a recursive definition, that is). So what about arrays of arrays? Sure enough, that works:

int[][] vectors = new int[3][];

An array with elements that are arrays by themselves is called a jagged array.

In the preceding example, we’re creating an array of integer arrays and specifying the number of such arrays we want. The vectors array contains arrays by itself, which are reference types. So right after the creation of the jagged array, it contains null references for the elements. Next, we can initialize those elements as follows:

vectors[0] = new int[4];vectors[1] = new int[2];vectors[2] = new int[3]; ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.