Fundamentals of Multidimensional Arrays and Classes

Introduction

Like an array of a primitive type, a multidimensional array can be made a field or property of a class. You can primarily declare it without initializing it. Here is an example:

public class TriangleInCoordinateSystem
{
    public int[,] Points;
}

This indicates a two-dimensional array field: the array will contain two lists but we don't (yet) know how many members each array will contain. Therefore, if you want, when creating the array, you can specify its dimension by assigning it a second pair of square brackets using the new operator and the data type. Here is an example:

public class TriangleInCoordinateSystem
{
    public int[,] Points = new int[3, 2];
}

You can also use a method of the class or a constructor to indicate the size of the array. Here is an example:

public class TriangleInCoordinateSystem
{
    private int[,] Points;

    public TriangleInCoordinateSystem()
    {
        Points = new int[3, 2];
    }
}

To initialize the array, you can access each member using the square brackets as we saw already. Here is an example:

public class TriangleInCoordinateSystem
{
    public int[,] Points;

    public TriangleInCoordinateSystem()
    {
        Points = new int[3, 2];

        Points[0, 0] = -2; // A(x, )
        Points[0, 1] = -3; // A( , y)
        Points[1, 0] =  5; // B(x, )
        Points[1, 1] =  1; // B( , y)
        Points[2, 0] =  4; // C(x, )
        Points[2, 1] = -2; // C( , y)
    }
}

In the same way, you can access the members of the array. For example, you can display their values to the user. Here is an example:

using static System.Console;

public class TriangleInCoordinateSystem
{
    public int[,] Points;

    public TriangleInCoordinateSystem()
    {
        Points = new int[3, 2];

        Points[0, 0] = -2; // A(x, )
        Points[0, 1] = -3; // A( , y)
        Points[1, 0] = 5; // B(x, )
        Points[1, 1] = 1; // B( , y)
        Points[2, 0] = 4; // C(x, )
        Points[2, 1] = -2; // C( , y)
    }
}

public class Exercise
{
    public static void Main()
    {
        TriangleInCoordinateSystem tics = new TriangleInCoordinateSystem();

        WriteLine("Geometry: Triangle");
        WriteLine("----------------------------");
        WriteLine("Coordinates of the Triangle:");
        WriteLine("A({0}, {1})\nB({2}, {3})\nC({4}, {5})",
                  tics.Points[0, 0], tics.Points[0, 1],
                  tics.Points[1, 0], tics.Points[1, 1],
                  tics.Points[2, 0], tics.Points[2, 1]);
        WriteLine("================================");
    }
}

This would produce:

Geometry: Triangle
----------------------------
Coordinates of the Triangle:
A(-2, -3)
B(5, 1)
C(4, -2)
================================
Press any key to continue . . .

A Multidimensional Array as Argument

A multidimensional array can be passed as argument. When creating the method, in its parentheses, enter the data type followed by the square brackets. In the square brackets, enter one comma for a two-dimensional array, two or more commas, as necessary, for a three-dimensional arrays as necessary. Here is an example:

public class TriangleInCoordinateSystem
{
    public void ShowPoints(int[,] Coords)
    {
    }
}

When defining the method, in its body, you can use the array as you see fit, such as displaying its values. To call this type of method, pass only the name of the array.

As indicated with one-dimensional arrays, when passing a multi-dimensional array as argument, the array is treated as a reference. This makes it possible for the method to modify the array and return it changed. If you want to indicate that the array is passed by reference, you can precede its data type in the parentheses by the the ref keyword.

Returning a Multi-Dimensional Array

You can return a multi-dimensional array from a method. When creating the method, before its name, specify the data type followed by square brackets. In the square brackets, enter the necessary number of commas. Here is an example:

public class TriangleInCoordinateSystem
{
    public int[,] CreateTriangle()
    {
    }
}

In the body of the method, you can do what you want but, before exiting it, you must return an array of the same type that was created. When calling the method, you can assign it to an array of the same type it returns. Here is an example:

public class TriangleInCoordinateSystem
{
    public int[,] CreateTriangle()
    {
        int[,] points = new int[3,2];

        points[0, 0] = -2; // A(x, )
        points[0, 1] = -3; // A( , y)
        points[1, 0] =  5; // B(x, )
        points[1, 1] =  1; // B( , y)
        points[2, 0] =  4; // C(x, )
        points[2, 1] = -2; // C( , y)

        return points;
    }
}

When calling the method, you can asign it to a local variable. Here is an example:

using static System.Console;

public class TriangleInCoordinateSystem
{
    public int[,] CreateTriangle()
    {
        int[,] points = new int[3, 2];

        points[0, 0] = -2; // A(x, )
        points[0, 1] = -3; // A( , y)
        points[1, 0] = 5; // B(x, )
        points[1, 1] = 1; // B( , y)
        points[2, 0] = 4; // C(x, )
        points[2, 1] = -2; // C( , y)

        return points;
    }
}

public class Exercise
{
    public static void Main()
    {
        TriangleInCoordinateSystem tics = new TriangleInCoordinateSystem();

        int[,] pts = tics.CreateTriangle();

        WriteLine("Geometry: Triangle");
        WriteLine("----------------------------");
        WriteLine("Coordinates of the Triangle:");
        WriteLine("A({0}, {1})\nB({2}, {3})\nC({4}, {5})",
                  pts[0, 0], pts[0, 1],
                  pts[1, 0], pts[1, 1],
                  pts[2, 0], pts[2, 1]);
        WriteLine("================================");
    }
}

If you are not plaanning to use the variable many times, you don't have to first declare a variable that would hold its returned array. You can call the method directly where the array is needed. Here are examples:

using static System.Console;

public class TriangleInCoordinateSystem
{
    public int[,] CreateTriangle()
    {
        int[,] points = new int[3, 2];

        points[0, 0] = -2; // A(x, )
        points[0, 1] = -3; // A( , y)
        points[1, 0] = 5; // B(x, )
        points[1, 1] = 1; // B( , y)
        points[2, 0] = 4; // C(x, )
        points[2, 1] = -2; // C( , y)

        return points;
    }
}

public class Exercise
{
    public static void Main()
    {
        TriangleInCoordinateSystem tics = new TriangleInCoordinateSystem();

        WriteLine("Geometry: Triangle");
        WriteLine("----------------------------");
        WriteLine("Coordinates of the Triangle:");
        WriteLine("A({0}, {1})\nB({2}, {3})\nC({4}, {5})",
                  tics.CreateTriangle()[0, 0], tics.CreateTriangle()[0, 1],
                  tics.CreateTriangle()[1, 0], tics.CreateTriangle()[1, 1],
                  tics.CreateTriangle()[2, 0], tics.CreateTriangle()[2, 1]);
        WriteLine("================================");
    }
}

A Multidimensional Array of Objects

A Variable of a Multidimensional Array of Objects

As done for primitive data types, you can create a multi-dimensional array where each member is of a class type. You can use an existing class or create a class. Here is an example:

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

To create a multidimensional array of objects without initializing it, you can use the following formula:

class-name[,] variable-name;

If you know the number of instances of the class that the array will use, you can use the following formula:

class-name[,] variable-name = new class-name[number1,number2];

You can use the var or the dynamic keyword in the following formula:

var variable-name = new data-type[number1,number2];
dynamic variable-name = new data-type[number1,number2];

The class-name is the name of the class that will represent each member of the array. The other sections follow the same rules we reviewed for the primitive types. For example, you can create an array without allocating memory for it as follows:

public class Exercise
{
    private void Create()
    {
        Coordinate[,] line;
    }
}

If you know the number of members that the array will contain, you can use the right pair of square brackets, in which case you can specify the name of the class or use the var keyword and omit the left square brackets. Here is an example:

public class Exercise
{
    private void Create()
    {
        Coordinate line = new Coordinate[2, 2];
    }
}

This declaration creates a two-dimensional array of two Coordinate objects: The array contains two lists and each list contains two Coordinate objects.

To initialize a multidimensional array of objects, you can access each array member using its index, and allocate memory for it using the new operator. After allocating memory for the member, you can then access its fields or properties to initialize it. Here is an example:

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Exercise
{
    public void Create()
    {
        Coordinate[,] line = new Coordinate[2, 2];

        line[0, 0] = new Coordinate(); // First Coordinate A
        line[0, 0].X = -3;             // A(x,  )
        line[0, 0].Y =  8;             // A( , y)
        line[0, 1] = new Coordinate(); // Second Coordinate B
        line[0, 1].X =  4;             // B(x,  )
        line[0, 1].Y = -5;             // B( , y)
    }
}

You can also initialize the array when creating it. Before doing this, you may need a constructor of the class. Such a constructor should take the argument(s) that would be used to initialize each member of the array. To actually initialize the array, you would need a pair of external curly brackets for the main array. Inside of the external curly brackets, create a pair of curly brackets for each sub-dimension of the array. Inside the last curly brackets, use the new operator to access an instance of the class and call its constructor to specify the values of the instance of the class. Here is an example:

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }

    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }
}

public class Exercise
{
    public void Create()
    {
        Coordinate[,] line = new Coordinate[,]
        {
            {
                new Coordinate(-3,  8),
				new Coordinate( 4, -5)
            }
        };
    }
}

Accessing the Members of a Multidimensional Array of Objects

To access the members of a multidimensional array of objects, apply the square brackets to a particular member of the array and access the desired field or property of the class. Here is an example:

using static System.Console;

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }

    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }
}

public class Geometry
{
    public static void Main()
    {
        Coordinate[,] line = new Coordinate[,]
        {
            {
                new Coordinate(-3,  8),
                new Coordinate( 4, -5)
            }
        };

        WriteLine("Geometry");
        WriteLine("--------------------------------");
        WriteLine("Line from A({0}, {1}) to B({2}, {3})",
                  line[0, 0].X, line[0, 0].Y,
                  line[0, 1].X, line[0, 1].Y);
        WriteLine("================================");
    }
}

This would produce:

Geometry
--------------------------------
Line from A(-3, 8) to B(4, -5)
================================
Press any key to continue . . .

You can also use a loop to access the members of the array. To do this, create a first for loop that stops at the first dimension of the array - 1. Then, inside of a first for loop, nest a for loop for each subsequent dimension.

To apply a foreach operator, access only each member of the internal list.

Multidimensional Arrays of Objects and Classes

Introduction

As done for primitive types, a multidimensional array of objects can be made a field of a class. You can declare the array without specifying its size. Here is an example:

public class Triangle
{
    public Coordinate[,] vertices;
}

If you know the dimensions that the array will have, you can specify them using the new operator at the same time you are creating the field. Here is an example:

public class Triangle
{
    public Coordinate[,] vertices = new Coordinate[3,2];
}

This creation signals a multidimensional array of Coordinate objects. It will consist of three lists and each list will contain two Coordinate objects

To initialize the array, access each member by its index to allocate memory for it. Once you get the member, you access each its fields or properties and initialize each with the desired value. Here is an example:

public class Triangle
{
    public Coordinate[,] vertices = new Coordinate[3, 2];

    public Triangle()
    {
        vertices[0, 0] = new Coordinate(); // Coordinate A(x, y)
        vertices[0, 0].x = -2;             // A(x,  )
        vertices[0, 0].y = -4;             // A( , y)
        vertices[1, 0] = new Coordinate(); // Coordinate B(x, y)
        vertices[1, 0].x =  3;             // B(x,  )
        vertices[1, 0].y =  5;             // B( , y)
        vertices[2, 0] = new Coordinate(); // Point C(x, y)
        vertices[2, 0].x =  6;             // C(x,  )
        vertices[2, 0].y = -2;             // C( , y)
    }
}

If the class is equipped with the right constructor, you can use it to initialize each member of the array.

Once the array is ready, you can access each members using its index and manipulate it. For example you can display its value(s) to the user. Here is an example:

using static System.Console;

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }

    public Coordinate()
    {

    }

    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }
}

public class Triangle
{
    public Coordinate[,] Vertices = new Coordinate[3, 2];

    public Triangle()
    {
        Vertices[0, 0] = new Coordinate(); // Coordinate A(x, y)
        Vertices[0, 0].X = -2;             // A(x,  )
        Vertices[0, 0].Y = -4;             // A( , y)
        Vertices[1, 0] = new Coordinate(); // Coordinate B(x, y)
        Vertices[1, 0].X = 3;             // B(x,  )
        Vertices[1, 0].Y = 5;             // B( , y)
        Vertices[2, 0] = new Coordinate(); // Point C(x, y)
        Vertices[2, 0].X = 6;             // C(x,  )
        Vertices[2, 0].Y = -2;             // C( , y)
    }
}

public class Geometry
{
    public static void Main()
    {
        Triangle tri = new Triangle();

        WriteLine("Geometry - Triangle");
        WriteLine("--------------------------------");
        WriteLine("Triangle Vertices:");
        WriteLine("A({0}, {1})\nB({2}, {3})\nC({4}, {5})",
                  tri.Vertices[0, 0].X, tri.Vertices[0, 0].Y,
                  tri.Vertices[1, 0].X, tri.Vertices[1, 0].Y,
                  tri.Vertices[2, 0].X, tri.Vertices[2, 0].Y);
        WriteLine("================================");
    }
}

This would produce:

Geometry - Triangle
--------------------------------
Triangle Vertices:
A(-2, -4)
B(3, 5)
C(6, -2)
================================
Press any key to continue . . .

Passing a Multidimensional Array of Objects

You can pass a multidimensional array of objects as arguments. To do this, in the parentheses of the method, enter the class name followed by the square brackets. In the square brackets, type the appropriate number of commas. Here is an example:

public class Triangle
{
    public void Create(Coordinate[,] points)
    {
    }
}

In the body of the method, use the array as we have done so far. You can access its members as we have done so far. For example, you can specify the values of the items of the array. Here are examples:

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Triangle
{
    public void Create(Coordinate[,] points)
    {
        points[0, 0] = new Coordinate(); // Point A(x, y)
        points[0, 0].X = -2;             // A(x,  )
        points[0, 0].Y = -4;             // A( , y)
        points[1, 0] = new Coordinate(); // Point B(x, y)
        points[1, 0].X =  3;             // B(x,  )
        points[1, 0].Y =  5;             // B( , y)
        points[2, 0] = new Coordinate(); // Point C(x, y)
        points[2, 0].X =  6;             // C(x,  )
        points[2, 0].Y = -2;             // C( , y)
    }
}

Remember that an array passed as argument is in fact passed by reference. This means that you can pass an empty array to a method; then in the body of the method, specify the values of the argument and use it in the body of the method. Here is an example:

using static System.Console;

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Triangle
{
    public void Create(Coordinate[,] points)
    {
        points[0, 0] = new Coordinate(); // Point A(x, y)
        points[0, 0].X = -2;             // A(x,  )
        points[0, 0].Y = -4;             // A( , y)
        points[1, 0] = new Coordinate(); // Point B(x, y)
        points[1, 0].X = 3;             // B(x,  )
        points[1, 0].Y = 5;             // B( , y)
        points[2, 0] = new Coordinate(); // Point C(x, y)
        points[2, 0].X = 6;             // C(x,  )
        points[2, 0].Y = -2;             // C( , y)

        WriteLine("Geometry - Triangle");
        WriteLine("--------------------------------");
        WriteLine("Triangle Vertices:");
        WriteLine("A({0}, {1})\nB({2}, {3})\nC({4}, {5})",
                  points[0, 0].X, points[0, 0].Y,
                  points[1, 0].X, points[1, 0].Y,
                  points[2, 0].X, points[2, 0].Y);
        WriteLine("================================");
    }
}

public class Geometry
{
    public static void Main()
    {
        Triangle tri = new Triangle();

        Title = "Geometry - Triangle";

        Coordinate[,] coords = new Coordinate[3, 2];

        tri.Create(coords);
    }
}

You can indicate this by preceding it with the ref keyword. Here is an example:

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Triangle
{
    public void Create(ref Coordinate[,] points)
    {
        points[0, 0] = new Coordinate(); // Point A(x, y)
        points[0, 0].X = -2;             // A(x,  )
        points[0, 0].Y = -4;             // A( , y)
        points[1, 0] = new Coordinate(); // Point B(x, y)
        points[1, 0].X =  3;             // B(x,  )
        points[1, 0].Y =  5;             // B( , y)
        points[2, 0] = new Coordinate(); // Point C(x, y)
        points[2, 0].X =  6;             // C(x,  )
        points[2, 0].Y = -2;             // C( , y)
    }
}

Returning a Multidimensional Array of Objects

A method can return a multidimensional array of objects. If you are creating the method, before its name, type the name of the class followed by square brackets. Inside the square brackets, type the desired number of commas to indicate the dimension of the returned value. Here is an example:

public class Triangle
{
    public Coordinate[, ] Create()
    {
    }
}

After implementing the method, before exiting it, make sure it returns the type of array that it was indicated to produce. Here is an example:

using static System.Console;

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Triangle
{
    public Coordinate[,] Create()
    {
        Coordinate[,] points = new Coordinate[3, 2];

        points[0, 0] = new Coordinate // Point A(x, y)
        {
            X = -2,                   // A(x,  )
            Y = -4                    // A( , y)
        };
        points[1, 0] = new Coordinate // Point B(x, y)
        {
            X = 3,                    // B(x,  )
            Y = 5                     // B( , y)
        };
        points[2, 0] = new Coordinate // Point C(x, y)
        {
            X = 6,                    // C(x,  )
            Y = -2                    // C( , y)
        };

        return points;
    }

    public void Display(Coordinate[,] points)
    {
        WriteLine("Geometry - Triangle");
        WriteLine("--------------------------------");
        WriteLine("Triangle Vertices:");
        WriteLine("A({0}, {1})\nB({2}, {3})\nC({4}, {5})",
                  points[0, 0].X, points[0, 0].Y,
                  points[1, 0].X, points[1, 0].Y,
                  points[2, 0].X, points[2, 0].Y);
        WriteLine("================================");
    }
}

public class Geometry
{
    public static void Main()
    {
        Triangle tri = new Triangle();

        Title = "Geometry - Triangle";

        Coordinate[,] coords = tri.Create();
        tri.Display(coords);
    }
}

In the above code, we first declared the array variable before setting its values. As an alternative, you can initialize the array when declaring the variable. Here is an example:

public class Triangle
{
    public Coordinate[,] Create()
    {
        Coordinate[,] points = new Coordinate[,]
        {
            {
                new Coordinate // Point A(x, y)
                {
                    X = -2,    // A(x,  )
                    Y = -4     // A( , y)
                }
            },
            {
                new Coordinate // Point B(x, y)
                {
                    X = 3,     // B(x,  )
                    Y = 5      // B( , y)
                }
            },
            {
                new Coordinate // Point C(x, y)
                {
                    X = 6,     // C(x,  )
                    Y = -2     // C( , y)
                }
            }
        };

        return points;
    }
}

Remember that, if you don't need to perform some primiary operations on the array, you create it directly after the return keyword. Here is an example:

public class Triangle
{
    public Coordinate[,] Create()
    {
        return new Coordinate[,]
        {
            {
                new Coordinate // Point A(x, y)
                {
                    X = -2,    // A(x,  )
                    Y = -4     // A( , y)
                }
            },
            {
                new Coordinate // Point B(x, y)
                {
                    X = 3,     // B(x,  )
                    Y = 5      // B( , y)
                }
            },
            {
                new Coordinate // Point C(x, y)
                {
                    X = 6,     // C(x,  )
                    Y = -2     // C( , y)
                }
            }
        };
    }
}

Jagged Arrays and Classes

Introduction

A jagged array of objects is an array where each element holds its own array of objects. Once again, all objects must be of the same type. This means that you must first have the class on which each object will be based. you can use one of the many .NET Framework built-in classes or you can create your own.

The formula to create a jagged array of objects is the same for primitive types. Specify the number of square brackets after the class name on the left side of the variable name. On the right side of the = operator, use the same number of square brackets. In the first brackets, specify the number of arrays. Here is an example:

public class State
{
    public string StateName { get; set; }
    public double Area      { get; set; }
    public string Capital   { get; set; }
}

public class CountriesStatistics
{
    public void Create()
    {
        State[][] states = new State[2][];
    }
}

You must then define each array by accessing its index and initialize each. Each array can have a different length. Here are starting examples:

public class State
{
    public string StateName { get; set; }
    public double Area { get; set; }
    public string Capital { get; set; }
}

public class Countries
{
    public void Create()
    {
        State[][] states = new State[2][];
    }
}

public class CountriesStatistics
{
    public static void Main()
    {
        State[][] states = new State[3][];

        // United States
        states[0] = new State[50];
        // Australia
        states[1] = new State[6];
        // Germany
        states[2] = new State[16];
    }
}

By accessing an array, you can initialize it using any of the techniques we have used so far. For example, to access the first array, apply index 0 in the first square brackets and the array's own index in the second square bracket. From there, access the member of the class. If it is a field or a property, you can assign the desired value to it. This can be done as follows:

public class State
{
    public string StateName { get; set; }
    public double Area { get; set; }
    public string Capital { get; set; }
}

public class CountriesStatistics
{
    public static void Main()
    {
        State[][] states = new State[3][];

        // United States
        states[0] = new State[50];
        // Australia
        states[1] = new State[6];
        // Germany
        states[2] = new State[16];

        states[1][0] = new State();
        states[1][0].StateName = "Western Australia (WA)";
        states[1][0].Area = 2645615;
        states[1][0].Capital = "Perth";
        states[1][1] = new State();
        states[1][1].StateName = "South Australia (SA)";
        states[1][1].Area = 1043514;
        states[1][1].Capital = "Adelaide";

    }
}

You can also initialize the whole array in a delimited curly bracket. Here is an example:

public class State
{
    public string StateName { get; set; }
    public double Area { get; set; }
    public string Capital { get; set; }
}

public class Countries
{
    public void Create()
    {
        State[][] states = new State[2][];
    }
}

public class CountriesStatistics
{
    public static void Main()
    {
        State[][] states = new State[3][];

        // United States
        states[0] = new State[50];
        // Australia
        states[1] = new State[6];
        // Germany
        states[2] = new State[16];

        states[1][0] = new State();
        states[1][0].StateName = "Western Australia (WA)";
        states[1][0].Area = 2645615;
        states[1][0].Capital = "Perth";
        states[1][1] = new State();
        states[1][1].StateName = "South Australia (SA)";
        states[1][1].Area = 1043514;
        states[1][1].Capital = "Adelaide";
        states[1][2] = new State();
        states[1][2].StateName = "Queensland (QLD)";
        states[1][2].Area = 1852642;
        states[1][2].Capital = "Brisbane";
        states[1][3] = new State();
        states[1][3].StateName = "New South Wales (NSW)";
        states[1][3].Area = 809444;
        states[1][3].Capital = "Sydney";
        states[1][4] = new State();
        states[1][4].StateName = "Victoria (VIC)";
        states[1][4].Area = 237639;
        states[1][4].Capital = "Melbourne";
        states[1][5] = new State();
        states[1][5].StateName = "Tasmania (TAS)";
        states[1][5].Area = 68401;
        states[1][5].Capital = "Hobart";

        // Germany
        states[2] = new State[]
        {
            new State() { StateName = "Saxony", Area = 18415.66, Capital = "Dresden" },
            new State() { StateName = "Lower Saxony", Area = 47614.07, Capital = "Hanover" },
            new State() { StateName = "Saxony-Anhalt", Area = 20451.58, Capital = "Magdeburg" },
            new State() { StateName = "Saarland", Area = 2570, Capital = "Saarbrücken" },
            new State() { StateName = "North Rhine-Westphalia", Area = 34084.13, Capital = "Düsseldorf" },
            new State() { StateName = "Berlin", Area = 891.70, Capital = "Berlin" },
            new State() { StateName = "Thuringia", Area = 16171, Capital = "Erfurt" },
            new State() { StateName = "Baden-Württemberg", Area = 35751.46, Capital = "Stuttgart" },
            new State() { StateName = "Hamburg", Area = 755, Capital = "Hamburg" },
            new State() { StateName = "Rhineland-Palatinate", Area = 19854.21, Capital = "Mainz" },
            new State() { StateName = "Schleswig-Holstein", Area = 15763.18, Capital = "Kiel" },
            new State() { StateName = "Brandenburg", Area = 29478.63, Capital = "Potsdam" },
            new State() { StateName = "Bavaria", Area = 70549.44, Capital = "Munich" },
            new State() { StateName = "Bremen ", Area = 419.38, Capital = "Bremen" },
            new State() { StateName = "Hesse", Area = 21100, Capital = "Wiesbaden" },
            new State() { StateName = "Mecklenburg-Vorpommern", Area = 15763.18, Capital = "Schwerin" }
       };
    }
}

Accessing the Items of a Jagged Array of Objects

Since a jagged array is an array of arrays, remember that each array has its own number of items. This means that you have many options to access the members of a jagged array. To start, to access one individual primary array, you can first specify its index in the left square brackets. From there, you can use the second square brackets to access an item of that particular array. Here is an example:

using static System.Console;

public class State
{
    public string StateName { get; set; }
    public double Area { get; set; }
    public string Capital { get; set; }
}

public class Countries
{
    public void Create()
    {
        State[][] states = new State[2][];
    }
}

public class CountriesStatistics
{
    public static void Main()
    {
        State[][] states = new State[3][];

        // United States
        states[0] = new State[50];
        // Australia
        states[1] = new State[6];
        // Germany
        states[2] = new State[16];

        states[1][0] = new State();
        states[1][0].StateName = "Western Australia (WA)";
        states[1][0].Area = 2645615;
        states[1][0].Capital = "Perth";
        states[1][1] = new State();
        states[1][1].StateName = "South Australia (SA)";
        states[1][1].Area = 1043514;
        states[1][1].Capital = "Adelaide";
        states[1][2] = new State();
        states[1][2].StateName = "Queensland (QLD)";
        states[1][2].Area = 1852642;
        states[1][2].Capital = "Brisbane";
        states[1][3] = new State();
        states[1][3].StateName = "New South Wales (NSW)";
        states[1][3].Area = 809444;
        states[1][3].Capital = "Sydney";
        states[1][4] = new State();
        states[1][4].StateName = "Victoria (VIC)";
        states[1][4].Area = 237639;
        states[1][4].Capital = "Melbourne";
        states[1][5] = new State();
        states[1][5].StateName = "Tasmania (TAS)";
        states[1][5].Area = 68401;
        states[1][5].Capital = "Hobart";

        // Germany
        states[2] = new State[]
        {
            new State() { StateName = "Saxony", Area = 18415.66, Capital = "Dresden" },
            new State() { StateName = "Lower Saxony", Area = 47614.07, Capital = "Hanover" },
            new State() { StateName = "Saxony-Anhalt", Area = 20451.58, Capital = "Magdeburg" },
            new State() { StateName = "Saarland", Area = 2570, Capital = "Saarbrücken" },
            new State() { StateName = "North Rhine-Westphalia", Area = 34084.13, Capital = "Düsseldorf" },
            new State() { StateName = "Berlin", Area = 891.70, Capital = "Berlin" },
            new State() { StateName = "Thuringia", Area = 16171, Capital = "Erfurt" },
            new State() { StateName = "Baden-Württemberg", Area = 35751.46, Capital = "Stuttgart" },
            new State() { StateName = "Hamburg", Area = 755, Capital = "Hamburg" },
            new State() { StateName = "Rhineland-Palatinate", Area = 19854.21, Capital = "Mainz" },
            new State() { StateName = "Schleswig-Holstein", Area = 15763.18, Capital = "Kiel" },
            new State() { StateName = "Brandenburg", Area = 29478.63, Capital = "Potsdam" },
            new State() { StateName = "Bavaria", Area = 70549.44, Capital = "Munich" },
            new State() { StateName = "Bremen ", Area = 419.38, Capital = "Bremen" },
            new State() { StateName = "Hesse", Area = 21100, Capital = "Wiesbaden" },
            new State() { StateName = "Mecklenburg-Vorpommern", Area = 15763.18, Capital = "Schwerin" }
       };

        WriteLine("Countries Statistics");
        WriteLine("==============================");
        WriteLine("Country - Australia");
        WriteLine("------------------------------");
        for (int i = 0; i < 6; i++)
            WriteLine("State: " + states[1][i].StateName);
        
        WriteLine("==============================");
    }
}

This would produce:

Countries Statistics
==============================
Country - Australia
------------------------------
State: Western Australia (WA)
State: South Australia (SA)
State: Queensland (QLD)
State: New South Wales (NSW)
State: Victoria (VIC)
State: Tasmania (TAS)
==============================
Press any key to continue . . .

You would use the same technique to access each primary array. Since the primary arrays may have different numbers of internal arrays, you can use a conditional statement to find out what array you are accessing at one particular time. Here is an example:

using static System.Console;

public class State
{
    public string StateName { get; set; }
    public double Area { get; set; }
    public string Capital { get; set; }
}

public class Countries
{
    public void Create()
    {
        State[][] states = new State[2][];
    }
}

public class CountriesStatistics
{
    public static void Main()
    {
        State[][] states = new State[3][];

        // United States
        states[0] = new State[50];
        // Australia
        states[1] = new State[6];
        // Germany
        states[2] = new State[16];

        states[1][0] = new State();
        states[1][0].StateName = "Western Australia (WA)";
        states[1][0].Area = 2645615;
        states[1][0].Capital = "Perth";
        states[1][1] = new State();
        states[1][1].StateName = "South Australia (SA)";
        states[1][1].Area = 1043514;
        states[1][1].Capital = "Adelaide";
        states[1][2] = new State();
        states[1][2].StateName = "Queensland (QLD)";
        states[1][2].Area = 1852642;
        states[1][2].Capital = "Brisbane";
        states[1][3] = new State();
        states[1][3].StateName = "New South Wales (NSW)";
        states[1][3].Area = 809444;
        states[1][3].Capital = "Sydney";
        states[1][4] = new State();
        states[1][4].StateName = "Victoria (VIC)";
        states[1][4].Area = 237639;
        states[1][4].Capital = "Melbourne";
        states[1][5] = new State();
        states[1][5].StateName = "Tasmania (TAS)";
        states[1][5].Area = 68401;
        states[1][5].Capital = "Hobart";

        // Germany
        states[2] = new State[]
        {
            new State() { StateName = "Saxony", Area = 18415.66, Capital = "Dresden" },
            new State() { StateName = "Lower Saxony", Area = 47614.07, Capital = "Hanover" },
            new State() { StateName = "Saxony-Anhalt", Area = 20451.58, Capital = "Magdeburg" },
            new State() { StateName = "Saarland", Area = 2570, Capital = "Saarbrücken" },
            new State() { StateName = "North Rhine-Westphalia", Area = 34084.13, Capital = "Düsseldorf" },
            new State() { StateName = "Berlin", Area = 891.70, Capital = "Berlin" },
            new State() { StateName = "Thuringia", Area = 16171, Capital = "Erfurt" },
            new State() { StateName = "Baden-Württemberg", Area = 35751.46, Capital = "Stuttgart" },
            new State() { StateName = "Hamburg", Area = 755, Capital = "Hamburg" },
            new State() { StateName = "Rhineland-Palatinate", Area = 19854.21, Capital = "Mainz" },
            new State() { StateName = "Schleswig-Holstein", Area = 15763.18, Capital = "Kiel" },
            new State() { StateName = "Brandenburg", Area = 29478.63, Capital = "Potsdam" },
            new State() { StateName = "Bavaria", Area = 70549.44, Capital = "Munich" },
            new State() { StateName = "Bremen ", Area = 419.38, Capital = "Bremen" },
            new State() { StateName = "Hesse", Area = 21100, Capital = "Wiesbaden" },
            new State() { StateName = "Mecklenburg-Vorpommern", Area = 15763.18, Capital = "Schwerin" }
       };

        WriteLine("Countries Statistics");
        WriteLine("==========================================");

        for (int i = 0; i < 3; i++)
        {
            if (i == 1)
            {
                WriteLine("Country - Australia");
                for (int j = 0; j < 6; j++)
                {
                    WriteLine("State: " + states[1][j].StateName);
                }
                WriteLine("------------------------------------------");
            }
            else if (i == 2)
            {
                WriteLine("Country - Germany");
                for (int j = 0; j < 16; j++)
                {
                    WriteLine("State: " + states[2][j].StateName);
                }
            }
        }

        WriteLine("==========================================");
    }
}

This would produce:

Countries Statistics
==========================================
Country - Australia
State: Western Australia (WA)
State: South Australia (SA)
State: Queensland (QLD)
State: New South Wales (NSW)
State: Victoria (VIC)
State: Tasmania (TAS)
------------------------------------------
Country - Germany
State: Saxony
State: Lower Saxony
State: Saxony-Anhalt
State: Saarland
State: North Rhine-Westphalia
State: Berlin
State: Thuringia
State: Baden-Württemberg
State: Hamburg
State: Rhineland-Palatinate
State: Schleswig-Holstein
State: Brandenburg
State: Bavaria
State: Bremen
State: Hesse
State: Mecklenburg-Vorpommern
==========================================
Press any key to continue . . .

Previous Copyright © 2008-2019, FunctionX Next