Loj Loj - 1 year ago 53
C# Question

How to safely check arrays bounds

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 boundaries. Can I handle this somehow instead of handling the exception?

Answer Source

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