user9993
user9993

Reputation: 6170

C# Printing a border around a 2D Array

I have a multidimensional array that I'm using as a box, and I have code that generates a border around it, like this:

#######
#     #
#     #
#     #
#     #
#######

However what I don't understand is that I can have either a 0 or a 1 in the "j == ProcArea.GetUpperBound(...)" part and it works successfully without any errors or unexpected output.

            int[,] ProcArea = new int[rows, columns];
            //Generate border
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    if (i == 0 || j == 0 || i == ProcArea.GetUpperBound(0) || j == ProcArea.GetUpperBound(1))
                    {
                        ProcArea[i, j] = 2;

                    }
                }
            }

Why does this work, and what is the correct value I should be using?

Thanks

Upvotes: 2

Views: 2448

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 133975

If the number of rows and columns are the same, then GetUpperBound(0) and GetUpperBound(1) are going to return the same value.

Arrays you create in C# (unless you call Array.CreateInstance directly) are always 0-based. So GetUpperBound(0) will always return rows - 1, and GetUpperBound(1) will always return columns - 1.

So the code will "work" regardless of which upper bound you check, although I think you'll find that if rows != columns, then using GetUpperBound(0) will create a different sized box than GetUpperBound(1).

By the way, an alternate way of making your border would be:

var maxRow = ProcArea.GetUpperBound(0);
var maxCol = ProcArea.GetUpperBound(1);
// do top and bottom
for (int col = 0; col <= maxCol; ++col)
{
    ProcArea[0, col] = 2;
    ProcArea[maxRow, col] = 2;
}
// do left and right
for (int row = 0; row <= maxRow; ++row)
{
    ProcArea[row, 0] = 2;
    ProcArea[row, maxCol] = 2;
}

It's slightly more code, true, but you don't waste time checking indexes unnecessarily. Won't make a difference with small arrays, of course.

Upvotes: 3

empi
empi

Reputation: 15881

Check the documentation http://msdn.microsoft.com/en-us/library/system.array.getupperbound.aspx. Your array has 2 dimensions (rows and columns).

ProcArea.GetUpperBound(0) is equivalent to rows - 1

ProcArea.GetUpperBound(1) is equivalent to columns - 1

Upvotes: 1

Related Questions