How to safely check array boundaries

I make life in a 2D array. I need to determine when all the neighboring cells are empty, so I just check all of them. It works well if the cell being checked is not a border. Then, of course, testing X + 1 throws an exception, since the index goes beyond the boundaries of the array. Can I handle this somehow instead of handling the exception? Thanks

+3
source share
4 answers

If you need speed, you have to process the edges differently and process the rest with

for(int x = 1; x < Size-1; x++)  // these all have x-1 and x+1 neighbours
+3
source

use GetLength(0)and GetLength(1)to get the width and height of the array.

, : casting to unsigned int, . , , .

(i >= 0) && (i < length)

(uint)i < length
+3

Yes, before accessing an element with an index i + 1, make sure that it is i + 1strictly inferior array.Length.

+1
source

I created an extension method for a 2D array to check if it is within the bounds:

public static class ExtensionMethods
{
    public static bool In2DArrayBounds(this object[,] array, int x, int y)
    {
        if (x < array.GetLowerBound(0) ||
            x > array.GetUpperBound(0) ||
            y < array.GetLowerBound(1) ||
            y > array.GetUpperBound(1)) return false;
        return true;
    }
}
+1
source

Source: https://habr.com/ru/post/1772243/


All Articles