Working With Rectangular Arrays in C#

Publish date: Apr 27, 2018
Tags: .net, c#

This quick and simple tutorial will help you get your head around the concept of multidimensional arrays in C# (and other languages too). Rectangular arrays are not that hard to understand, once you can visualize them in your mind, and know the basic syntax for your programming language of choice. Ready? Let`s go!

using System;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,,] cubeOfInts = {
                {
                    {1,2,3},
                    {4,5,6},
                    {7,8,9}
                },
                {
                    {10,11,12},
                    {13,14,15},
                    {16,17,18}   
                },
                {
                    {19,20,21},
                    {22,23,24},
                    {25,26,27}   
                }
            };

            int bottomBackRightCorner = cubeOfInts[2,2,2];
            Console.WriteLine(bottomBackRightCorner);
        }
    }
}
dotnet run
27

…as you can see, it will print out 27, which (if you imagine this 3d array as a cube that is facing you) is at the BACK[2], BOTTOM[2], RIGHT[2] corner. The declaration of 3d rectangular array goes like: int[,,] = …; 2d would be int[,], 1d would be int[] Each layer of rectangular brackets {} separates the dimensions. We can have as many as we want, but beyond 3d it is a little bit hard to imagine (for me at least) the actual use of this array. Now that we have declared an array, how do we pick a number from it? Say bottom back right corner? Let me explain using a helpful tool.

Rubik’s Cube

Imagine a Rubik`s Cube, which this in a sense is. Put it on the table so that one side is facing you. What is it composed of? Little cubes, 3*3*3 of them => 27. If you slice it to 3 pieces based on how close it is to you, you get 3 layers, composed of 3x3 pieces (ints). In C# they are indexed, closest one to you is 0, next one is 1, and finally 2. So pick 2. Now we have 2d layer of 3x3 and we want bottom right int, what do we do? We pick the 3rd row, which is also indexed by 2. Ok now we are left with {25,26,27}, so we pick index 2 again! Which gives us 27. That is exactly what we did in the code: ‘cubeOfInts[2,2,2]‘. I hope you came here having no idea what a rectangular array in C# is, and now think there is nothing easier in whole .NET than rectangular arrays. :smile: