开发者

How to safely check arrays bounds

开发者 https://www.devze.com 2023-01-22 22:24 出处:网络
I am making game of life in 2D array. I need to determine when all adjacent cells are empty so I just test all of them. It works well unless the cell being checked is the boundary. Then of course test

I am making game of life in 2D array. I need to determine when all adjacent cells are empty so I just test all of them. It works well unless the cell being checked is the boundary. Then of course testing X+1 throws an exception as the index is out of the array bound开发者_StackOverflow中文版aries. Can I handle this somehow instead of handling the exception? Thanks


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

There is also a neat performance trick the runtime uses for its own bounds checks: casting to unsigned int to reduce the two checks into one. But since this costs readability you use it if the check is really performance critical.

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

becomes

(uint)i < length


If you want speed you'll have to treat the edge-cells differently and process the rest with a

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


I created an extension method for a 2D array to check if in 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;
    }
}


Yes, before accessing the element at index i + 1, check whether i + 1 is strictly inferior to array.Length.

0

精彩评论

暂无评论...
验证码 换一张
取 消