How can I check if array is out of range.
i use int[,] and I want to know how to check if lets say variable[11,9] is out of range if i set int[,] to be [10,10]?
because error stops whole script
(array).GetLength(dimension);
So if you want to check if 11,9 is out of range, check if 11 is greater than (array).GetLength(0) and if 9 is greater than (array).GetLength(1)
int[,] is implemented as an array of arrays. For my example, some you initialized an int[,] as
var matrix = new int[,] { {1, 2, 3}, {4, 5}, {6, 7, 8} };
You can check your first indexer against matrix.length. You’ll notice my matrix has different sized sub arrays. This is allowed, which means the second indexer will need to be checked for each sub array.
matrix.length is 3
matrix[0].length is 3
matrix[1].length is 2
etc…
So i should check
If (x>=0 && x<array.getlength(0))
Print(“inside”);
So in this case 0 checks rows and 1 colums in getlength?
The array you defined is a 2D array. As such, it represents a table-like set of data (thinks rows and columns). Think of the 2D array as follows: the first index, x, represents the current column, and the second index, y, represents the value within the column. All the above code does is check that the index falls inside of the bounds of the x-index, that is, falls on a valid column. GetLength(0) would be the length of the column, and GetLength(1) would be the length of the row, in this case.
Hmm I must have been thinking of a different language - C# does not allow jagged arrays like I suggested. You can still use the approach I gave but I think I like @RiokuTheSlayer 's GetLength method better.
You can think of the rows and columns in whichever order you like, though I think the unspoken standard is to list columns first and rows second. Just be sure that you test your first parameter against GetLength(0) and second against GetLength(1). GetLength isn’t just for 2D arrays either; it can be used for an array of any rank up to 32 dimensions (though array’s are capped at 2GB size, so you’ll probably get an out of memory exception pretty quick!)
i used getlength metod as 0 was describing rows and 1 columns
thanks for help
C# does allow jagged Arrays: int[ ][ ]
Ahh. I stand corrected.