Home

Multidimensional Arrays and Classes

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 System;
using System.Windows.Forms;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            TriangleInCoordinateSystem tri = new TriangleInCoordinateSystem();

            tri.ShowPoints();
        }
    }
    public class TriangleInCoordinateSystem
    {
        private 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 void ShowPoints()
        {
            string strCoordinates = "Coordinates of the Triangle" + Environment.NewLine +
                                    "A(" + points[0, 0] + ", " + points[0, 1] + ")" + Environment.NewLine +
                                    "B(" + points[1, 0] + ", " + points[1, 1] + ")" + Environment.NewLine +
                                    "C(" + points[2, 0] + ", " + points[2, 1] + ")";
            MessageBox.Show(strCoordinates,
                            "Coordinate System",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
        }
    }
}

This would produce:

Multidimensional Arrays and Classes

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. Here is an example:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            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)

            TriangleInCoordinateSystem tri = new TriangleInCoordinateSystem();

            tri.ShowPoints(points);
        }
    }

    public class TriangleInCoordinateSystem
    {
        public void ShowPoints(int[,] coords)
        {
            string strCoordinates = "Coordinates of the Triangle" + Environment.NewLine +
                                    "A(" + coords[0, 0] + ", " + coords[0, 1] + ")" + Environment.NewLine +
                                    "B(" + coords[1, 0] + ", " + coords[1, 1] + ")" + Environment.NewLine +
                                    "C(" + coords[2, 0] + ", " + coords[2, 1] + ")";

            MessageBox.Show(strCoordinates, "Coordinate System",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

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. Here is an example:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            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)

            TriangleInCoordinateSystem tri = new TriangleInCoordinateSystem();

            tri.ShowPoints(ref points);
        }
    }

    public class TriangleInCoordinateSystem
    {
        public void ShowPoints(ref int[,] coords)
        {
            string strCoordinates = "Coordinates of the Triangle" + Environment.NewLine +
                                    "A(" + coords[0, 0] + ", " + coords[0, 1] + ")" + Environment.NewLine +
                                    "B(" + coords[1, 0] + ", " + coords[1, 1] + ")" + Environment.NewLine +
                                    "C(" + coords[2, 0] + ", " + coords[2, 1] + ")";

            MessageBox.Show(strCoordinates, "Coordinate System",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
} int[,] coords)
    {
        string strCoordinates = "Coordinates of the Triangle" + NewLine +
                                "A(" + coords[0, 0] + ", " + coords[0, 1] + ")" + NewLine +
                                "B(" + coords[1, 0] + ", " + coords[1, 1] + ")" + NewLine +
                                "C(" + coords[2, 0] + ", " + coords[2, 1] + ")";

        Show(strCoordinates, "Coordinate System",
             System.Windows.Forms.MessageBoxButtons.OK,
             System.Windows.Forms.MessageBoxIcon.Information);
    }
}

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:

using System;

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:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            int[,] points = new int[3, 2];

            TriangleInCoordinateSystem tri = new TriangleInCoordinateSystem();

            points = tri.CreateTriangle();
            tri.ShowPoints(ref points);
        }
    }

    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 void ShowPoints(ref int[,] coords)
        {
            string strCoordinates = "Coordinates of the Triangle" + Environment.NewLine +
                                    "A(" + coords[0, 0] + ", " + coords[0, 1] + ")" + Environment.NewLine +
                                    "B(" + coords[1, 0] + ", " + coords[1, 1] + ")" + Environment.NewLine +
                                    "C(" + coords[2, 0] + ", " + coords[2, 1] + ")";

            MessageBox.Show(strCoordinates, "Coordinate System",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

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 static class Exercise
{
    static int Main(string[] args)
    {
        Coordinate[,] line;

        return 0;
    }
}

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 static class Exercise
{
    static int Main(string[] args)
    {
        Coordinate line = new Coordinate[2, 2];

        return 0;
    }
}

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 static int Main(string[] args)
    {
        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)

        return 1;
    }
}

You can also initialize the array when creating it. Before doing this, you would need a constructor of the class and the constructor must 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 static class Exercise
{
    static int Main(string[] args)
    {
        Coordinate[,] line = new Coordinate[,]
        {
            {
                new Coordinate(-3,  8),
                new Coordinate( 4, -5)
            }
        };

        return 0;
    }
}

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 System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Coordinate[,] line = new Coordinate[,]
            {
                {
                    new Coordinate(-3, 8),
                    new Coordinate(4, -5)
                }
            };

            MessageBox.Show("Line =-=" + NewLine +
                            "From A(" + line[0, 0].X + ", " + line[0, 0].Y +
                            " to B("  + line[0, 1].X + ", " + line[0, 1].Y + ")",
                            "Geometry", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

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

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

This would produce:

Accessing the Members of the Array

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. Here is an example:

using System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Coordinate[,] line = new Coordinate[,]
            {
                {
                    new Coordinate(-3, 8),
                    new Coordinate(4, -5)
                }
            };

            string strLine = "The points of the line are:" + NewLine;

            for (int i = 0; i < 1; i++)
                for (int j = 0; j < 2; j++)
                    strLine += "(" + line[i, j].X + ", " + line[i, j].Y + ")" + NewLine;

            MessageBox.Show(strLine, "Geometry", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

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

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

This would produce:

Accessing the Members of the Array

To apply a foreach operator, access only each member of the internal list. Here is an example:

using System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Coordinate[,] line = new Coordinate[,]
            {
                {
                    new Coordinate(-3, 8),
                    new Coordinate(4, -5)
                }
            };

            string strLine = "The points of the line are:" + NewLine;

            foreach (Coordinate coord in line)
                strLine += "(" + coord.X + ", " + coord.Y + ")" + NewLine;

            MessageBox.Show(strLine, "Geometry", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

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

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

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 System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Triangle tri = new Triangle();
            tri.Identify();
        }
    }

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

        public Coordinate()
        {
            X = 0;
            Y = 0;
        }

        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(); // Point A(x, y)
            vertices[0, 0].X = -2;             // A(x,  )
            vertices[0, 0].Y = -4;             // A( , y)
            vertices[1, 0] = new Coordinate(); // Point 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 void Identify()
        {
            string strTriangle = "Triangle Vertices: " + NewLine +
                                 "A(" + vertices[0, 0].X + ", " + vertices[0, 0].Y +
                                 "),  B(" + vertices[1, 0].X + ", " + vertices[1, 0].Y +
                                 "), and C(" + vertices[2, 0].X + ", " + vertices[2, 0].Y + ")";

            MessageBox.Show(strTriangle, "Geometry - Triangle Coordinates",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

This would produce:

Introduction to Multidimensional Arrays of Objects and Classes

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 you we have done so far. You can access its members to get to its values. Here are examples:

using System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Triangle tri = new Triangle();
            Coordinate[,] coords = new Coordinate[3, 2];

            tri.Create(coords);
            tri.Identify(coords);
        }
    }

    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)
        }

        public void Identify(Coordinate[,] vertices)
        {
            string strTriangle = "Triangle Vertices: " + NewLine +
                                 "A(" + vertices[0, 0].X + ", " + vertices[0, 0].Y +
                                 "),  B(" + vertices[1, 0].X + ", " + vertices[1, 0].Y +
                                 "), and C(" + vertices[2, 0].X + ", " + vertices[2, 0].Y + ")";

            MessageBox.Show(strTriangle,
                "Geometry - Triangle Coordinates", System.Windows.Forms.MessageBoxButtons.OK,
                System.Windows.Forms.MessageBoxIcon.Information);
        }
    }
}

Remember that an array passed as argument is in fact passed by reference. You can indicate this by preceding it with the ref keyword. Here is an example:

using System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Triangle tri = new Triangle();
            Coordinate[,] coords = new Coordinate[3, 2];

            tri.Create(ref coords);
            tri.Identify(coords);
        }
    }

    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)
        }

        public void Identify(Coordinate[,] vertices)
        {
            string strTriangle = "Triangle Vertices: " + NewLine +
                                 "A(" + vertices[0, 0].X + ", " + vertices[0, 0].Y +
                                 "),  B(" + vertices[1, 0].X + ", " + vertices[1, 0].Y +
                                 "), and C(" + vertices[2, 0].X + ", " + vertices[2, 0].Y + ")";

            MessageBox.Show(strTriangle, "Geometry - Triangle Coordinates",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

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 System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            Triangle tri = new Triangle();
            Coordinate[,] coords = tri.Create();
            tri.Identify(coords);
        }
    }

    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)
            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)

            return points;
        }

        public void Identify(Coordinate[,] vertices)
        {
            string strTriangle = "Triangle Vertices: " + NewLine +
                                 "A(" + vertices[0, 0].X + ", " + vertices[0, 0].Y +
                                 "),  B(" + vertices[1, 0].X + ", " + vertices[1, 0].Y +
                                 "), and C(" + vertices[2, 0].X + ", " + vertices[2, 0].Y + ")";

            MessageBox.Show(strTriangle, "Geometry - Triangle Coordinates",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

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 Exercise
{
    public static int Main(string[] args)
    {
        State[][] states = new State[2][];

        return 10_101;
    }
}

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 Exercise
{
    public static int Main(string[] args)
    {
        State[][] states = new State[3][];

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

        return 12_010;
    }
}

By accessing an array, you can initialize it using any of the techniques we have used so far. For example, to access the first artray, apply index 0 in the first square brackets and the arrays 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:

states[0] = new State[6];
        
states[0][0] = new State();
states[0][0].StateName = "Western Australia (WA)";
states[0][0].Area = 2645615f;
states[0][0].Capital = "Perth";
states[0][1] = new State();
states[0][1].StateName = "South Australia (SA)";
states[0][1].Area = 1043514f;
states[0][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 float Area       { get; set; }
    public string Capital   { get; set; }
}

public class Exercise
{
    public static int Main(string[] args)
    {
        State[][] states = new State[2][];

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

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

        return 0;
    }
}

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 System;
using System.Windows.Forms;
using static System.Environment;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnArray_Click(object sender, EventArgs e)
        {
            State[][] states = new State[2][];

            // Australia
            states[0] = new State[6];

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

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

            for (int i = 0; i < 6; i++)
                MessageBox.Show("State: " + states[0][i].StateName, "States Statistics - Australia");
        }
    }

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

This would produce:

Accessing the Items of a Jagged Array of Objects Accessing the Items of a Jagged Array of Objects
Accessing the Items of a Jagged Array of Objects Accessing the Items of a Jagged Array of Objects
Accessing the Items of a Jagged Array of Objects Accessing the Items of a Jagged Array of Objects

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 access at one particular time. Here is an example:

using System.Windows.Forms;

namespace WindowsFormsApplications
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ShowAustralia();
        }

        void ShowAustralia()
        {
            State[][] states = new State[2][];

            // Australia
            states[0] = new State[6];

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

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

            ListViewItem lviCountry = null;

            for (int i = 0; i < 2; i++)
            {
                int counter = 1;

                if (i == 0)
                {
                    for (int j = 0; j < 6; j++)
                    {
                        lviCountry = new ListViewItem(counter.ToString());

                        lviCountry.SubItems.Add(states[0][j].Abbreviation);
                        lviCountry.SubItems.Add(states[0][j].StateName);
                        lviCountry.SubItems.Add(states[0][j].Area.ToString());
                        lviCountry.SubItems.Add(states[0][j].Capital);
                        lvwAustralia.Items.Add(lviCountry);

                        counter++;
                    }
                }
                else // if( i == 1)
                {
                    counter = 1;

                    for (int j = 0; j < 16; j++)
                    {
                        lviCountry = new ListViewItem(counter.ToString());

                        lviCountry.SubItems.Add(states[1][j].StateName);
                        lviCountry.SubItems.Add(states[1][j].Area.ToString());
                        lviCountry.SubItems.Add(states[1][j].Capital);
                        lvwGermany.Items.Add(lviCountry);

                        counter++;
                    }
                }
            }
        }
    }

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

This would produce:

Accessing the Items of a Jagged Array of Objects


Previous Copyright © 2008-2020, FunctionX Next