I am trying to write a method that checks, if a given x/y pair is a valid index for a 2nd array (eg check if myArray[x,y]
is safe).
I would like it to work with arrays of any type, which I feel should be possible because they all have the same GetUpperBounds(int d) method and I do not need to touch their contents. I have tried
bool validate(<T>[,] array, int x, int y){ ... }
and
bool validate([,] array, int x, int y){ ... }
but that does not work.
Should I just keep overloading this method as needed even though the method bodies will be identical character for character?
The right syntax is:
bool validate<T>(T[,] array, int x, int y)
{
}
with the code inside that should be:
bool validate<T>(T[,] array, int x, int y)
{
return x >= array.GetLowerBound(0) && x <= array.GetUpperBound(0) &&
y >= array.GetLowerBound(1) && y <= array.GetUpperBound(1);
}
Or ignoring array that have a lower bound != 0... (you can create arrays that have the first index at 100, so that myarray[100]
is the first element. It was done for compatibility with old VB probably. It isn't very used)
bool validate<T>(T[,] array, int x, int y)
{
return x >= 0 && x < array.GetLength(0) &&
y >= 0 && y < array.GetLength(1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With