C Sharp

Jagged Arrays

The last thing we'll look at with regard to arrays is the jagged array. A jagged array is simply an array of arrays. Here's an example of defining an array containing integer arrays: -

int[][] jaggedArray;

You might use a jagged array if you were developing an editor. In this editor, you might want to store the object representing each user-created control in an array. Let's say you had an array of buttons and combo boxes (to keep the example small and manageable). You might have three buttons and two combo boxes both stored in their respective arrays. Declaring a jagged array enables you to have a "parent" array for those arrays so that you can easily programmatically iterate through the controls when you need to, as shown here: -

using System;
class Control
{
    virtual public void SayHi()
    {
        Console.WriteLine("base control class");
    }
}
class Button : Control
{
    override public void SayHi()
    {
        Console.WriteLine("button control");
    }
}
class Combo : Control
{
    override public void SayHi()
    {
        Console.WriteLine("combobox control");
    }
}
class JaggedArrayApp
{
    public static void Main()
    {
    Control[][] controls;
    controls = new Control[2][];
    controls[0] = new Control[3];
    for (int i = 0; i < controls[0].Length; i++)
    {
        controls[0][i] = new Button();
    }
    controls[1] = new Control[2];
    for (int i = 0; i < controls[1].Length; i++)
    {
        controls[1][i] = new Combo();
    }
    for (int i = 0; i < controls.Length;i++)
    {
        for (int j=0;j< controls[i].Length;j++)
        {
            Control control = controls[i][j];
            control.SayHi();
        }
    }
    string str = Console.ReadLine();
    }
}

As you can see, I've defined a base class (Control) and two derived classes (Button and Combo) and I've declared the jagged array as an array of arrays that contain Controls objects. That way I can store the specific types in the array and, through the magic of polymorphism, know that when it's time to extract the objects from the array (through an upcasted object) I'll get the behavior I expect.