Jagged Array in C# with simple example
A. What is Jagged Array ?
Jagged array is known as Array of arrays. It means that, a Jagged Array contains different
arrays as its elements. Elements of jagged array can be
of different dimension and size.
B. Declaring a Jagged Array :
string[][] simpleJagged = new string[3][];
C. Initializing a Jagged Array :
a.
We can initialize the elements like this :
simpleJagged[0] = new string[3];
simpleJagged[1] = new string[4];
simpleJagged[2] = new string[5];
b.
To initialize elements with values, we can use initializers.
simpleJagged[0] = new string[] { "Red", "Green", "Blue" };
simpleJagged[1] = new string[] { "Pune", "Mumbai", "Hyd", "Banglore" };
simpleJagged[2] = new string[] { "Amol", "John", "Suraj", "Ram", "Steve" };
We dont need to provide array size while using initializers.
c.
We can also declare and initialize jagged array as follows :
string[][] simpleJagged =
{
new string[] { "Red", "Green", "Blue" },
new string[] { "Pune", "Mumbai", "Hyd", "Banglore" },
new string[] { "Amol", "John", "Suraj", "Ram", "Steve" }
};
This example shows that simpleJagged is an array of 3 arrays. simpleJagged[0] is an array of 3 strings,
simpleJagged[1] is an array of 4 strings, simpleJagged[2] is an array of 5 strings.
D. Accessing Individual Array Elements :
We can access individual elements as follows:
Console.WriteLine(simpleJagged[0][0]);
// It will print first element of first array i. e. "Red"
Console.WriteLine(simpleJagged[1][2]);
// It will print third element of second array i. e. "Hyd"
Console.WriteLine(simpleJagged[2][1]);
// It will print second element of third array i. e. "John"
E. Example of Jagged Array :
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string[][] simpleJagged =
{
new string[] { "Red", "Green", "Blue" },
new string[] { "Pune", "Mumbai", "Hyd", "Banglore" },
new string[] { "Amol", "John", "Suraj", "Ram", "Steve" }
};
Console.Write("Colors : ");
for (int i = 0; i < simpleJagged[0].Length; i++)
Console.Write(simpleJagged[0][i] + "\t");
Console.WriteLine();
Console.Write("Cities : ");
for (int i = 0; i < simpleJagged[1].Length; i++)
Console.Write(simpleJagged[1][i] + "\t");
Console.WriteLine();
Console.Write("Names : ");
for (int i = 0; i < simpleJagged[2].Length; i++)
Console.Write(simpleJagged[2][i] + "\t");
Console.ReadKey();
}
}
}