Jagged Array in C# with Example – Programming, Pseudocode Example, C# Programming Example
Arrays C# For Loop Loops / Iteration Statement

Jagged Array in C# with Example

A jagged array in C# is a multi-dimensional array comprising arrays of varying sizes as its elements. It’s also referred to as “an array of arrays” or “ragged array”.

In this quick tutorial, we’ll look more in-depth into defining and working with jagged arrays.

Creating Jagged Array

Using the Shorthand-Form

An easy way to define a jagged array would be:

Here, we’ve declared and initialized jaggedArr in a single step

 

Declaration and then Initialization

The length of the first dimension is 3.The declaration can be read as “jagArr is an array of three arrays of ints.”

A jagged array can be of any number of dimensions greater than one.In rectangular arrays, dimension lengths cannot be included in the array type section of the declaration.

Syntax for jagged arrays requires a separate set of square brackets for each dimension. The number of sets of square brackets in the declaration of the array variable determines the rank of the array.

 

Here, we’ve omitted to specify the second dimension since it will vary.

Next, let’s go further by both declaring and initializing the respective elements within jaggedArr:

Memory Representation

How will the memory representation of our jaggedArr look like?

As we know, an array in C# is nothing but an object, the elements of which could be either primitives or references. So, a two-dimensional array in C# can be thought of as an array of one-dimensional arrays.

Our jaggedArr in memory would look similar to:

Clearly, jaggedArr[0] is holding a reference to a single-dimensional array of size 2,jaggedArr[1] holds a reference to another one-dimensional array of size 3 and so on.

This way C# makes it possible for us to define and use jagged arrays.

 Iterating and Printing Elements Example

Output:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.