TechieClues TechieClues
Updated date Dec 20, 2021
In this blog, we will learn how to declare, getting and setting jagged arrays. Jagged arrays are arrays in which member arrays can be of different sizes. It's like an array of arrays - each array element contains another array.
  • 1.8k
  • 0
  • 0

Jagged arrays are arrays in which member arrays can be of different sizes. It's like an array of arrays - each array element contains another array.

Jagged arrays are similar to multidimensional arrays, but have a minor difference. The multidimensional arrays have a fixed number of rows and columns where the jagged arrays can have a different number of columns in every row.

How to declare a jagged array?

For this example, declaring a jagged array with 5 columns:

int[][] x = new int[5][];

The second [] is initialized without a number. To initialize the sub-arrays, we need to do that separately as shown below,

for (int i = 0; i < x.length; i++) 
{
    x[i] = new int[10];
}

How to Get/Set values in a jagged array?

Now, getting one of the subarrays is easy. Let's print all the numbers of the 4th column of a:

for (int i = 0; i < x[3].length; i++)
{
    Console.WriteLine(x[3][i]);
}

Get a specific value:

x[<row_number>][<column_number>]

Set a specific value:

x[<row_number>][<column_number>] = <value>

Note: Jagged arrays (arrays of arrays) are faster and safe to use so use jagged arrays rather than multidimensional arrays (matrixes).

Order of the brackets to Note:

Consider a four-dimensional array of six-dimensional arrays of one-dimensional arrays of int. This should be written in C# as:

int[,,,][,,,,,][] arr = new int[3, 2, 10,6][,,,,,][];

In the CLR type system, the convention for the ordering of the brackets is reversed, so with the above arr the instance we have:

arr.GetType().ToString() == "System.Int32[][,,,,,][,,,]"

and likewise:

typeof(int[,,,][,,,,,][]).ToString() == "System.Int32[][,,,,,][,,,]"

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!