c# Jagged Arrays

While working on a new game app, I needed to initialized a multi-dimensional array upon declaration.  I initially used a two dimensional array declared as such:

readonly TrackType[,] validTypes = {{TrackType.none},
{TrackType.one, TrackType.two, TrackType.three}};

This worked fine and the array was declared and initialized correctly.  I then decided I wanted to extract a row from this array and work on it, rather than always using two indexes as I processed the entries.  However, with a multi-dimensional array it’s not possible to do this implicitly.  The solution was to create a Jagged Array.  Each element is accessed in a similar way, but it allows you to grab a pointer to a row of the array, which is what I wanted.

The syntax for defining and initializing it during declaration is quite different however, and this is what I ended up with:

readonly TrackType[][] validTypes = new TrackType[][] {
new TrackType[] {TrackType.none},
new TrackType[] {TrackType.one, TrackType.two, TrackType.three}};

More typing, but it gets the job done.

Leave a Reply