Weavermount
Weavermount

Reputation: 746

C#: Passing generic arrays

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?

Upvotes: 4

Views: 6041

Answers (1)

xanatos
xanatos

Reputation: 111860

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);
}

Upvotes: 7

Related Questions