Check if a key in an array exists

MrLucky

Freshman
Joined
Mar 5, 2006
Messages
47
How can I check if a key in an array exists without getting an Out of Bounds exception?

Thanks in advance :)
 
If it's a regular array, compare the index to the Length:
C#:
string[] test = new string[25]; // Count will be 25, indexes 0 through 24
...
private string GetValue(int index)
{
    if (index > (test.Length - 1))
    {
        // Handle an index that's too big
    }
    else
    {
        return test[index];
    }
}

-nerseus
 
Not to nitpick; but a function like that should probably check for negitive index values as well as ones that are too big.

I suppose it's a matter of personal opinion; but I tend to do as much error checking as is reasonably possible; because I know in a week I wont remember what the function does and I will try to pass it god knows what....
 
That would be more thorough, but to be honest, I have never used a non-zero based array in .Net. They don't really make sense and you have to go through extra trouble to create them. As far as my program practices go, I don't way out of the way for error checking because if a particularly unusual object, such as a non-zero based array, makes its way into the code, it isn't what was expected and I would consider it invalid input which should constitute an error. Exceptions are like my way of saying "Hey *******, what kind of array is that?" (Besides, Nerseus said "If it's a regular array.")
 
Actually, if I were writing a safe function, I'd want to check negative values - I was trying to demonstrate a check against the Length property.

I hate out of bounds exceptions but glad that there's no memory leakage or buffer overflows :)

-ner
 
Back
Top