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# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.