Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely check arrays bounds

Tags:

arrays

c#

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? Thanks

like image 482
Loj Avatar asked Oct 30 '10 10:10

Loj


2 Answers

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
like image 132
CodesInChaos Avatar answered Oct 18 '22 22:10

CodesInChaos


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
like image 34
Henk Holterman Avatar answered Oct 18 '22 20:10

Henk Holterman