Jagged Arrays in C#

In this post, we will learn about Jagged Arrays in C# with an example.

Description

A Jagged array is an array of arrays. Jagged Array is also called “array of arrays” because its elements are arrays. The element size of a jagged array can be different.

Types of Arrays in C#

Arrays can be divided into the following three categories.

Declaration of Jagged Array

Declare jagged array that has two elements.

  1. int[][] _RollNumber = new int[2][];
Initialization of Jagged Array

Write the below lines to initialize a Jagged Array. The size of the elements can be different.

  1. _RollNumber[0] = new int[2];
  2. _RollNumberr[1] = new int[3];
Now, create a Console Application in Visual Studio and write the below lines of code in it.
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace ConsoleDemo
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. // Jagged Array Example
  11. int[][] _JaggedArrayExample = new int[2][];// Declare jagged array
  12. _JaggedArrayExample[0] = new int[] { 11, 21, 31, 41 };// Initialize the array with value
  13. _JaggedArrayExample[1] = new int[] { 42, 52, 62, 72, 83, 93 };
  14. // Raed and print array elements
  15. for (int i = 0; i < __JaggedArrayExample.Length; i++)
  16. {
  17. for (int j = 0; j < __JaggedArrayExample[i].Length; j++)
  18. {
  19. System.Console.Write(__JaggedArrayExample[i][j] + " ");
  20. }
  21. System.Console.WriteLine();
  22. }
  23. Console.ReadKey();
  24. }
  25. }
  26. }
Output

11 21 31 41
42 52 62 72 83 93

Summary

I hope you understood Jagged Arrays in C#. Your valuable questions, feedback, or comments about this article are always welcome.