MrLucky Posted March 8, 2006 Posted March 8, 2006 How can I check if a key in an array exists without getting an Out of Bounds exception? Thanks in advance :) Quote
*Experts* Nerseus Posted March 8, 2006 *Experts* Posted March 8, 2006 If it's a regular array, compare the index to the Length: 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 Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Nate Bross Posted March 8, 2006 Posted March 8, 2006 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.... Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
Leaders snarfblam Posted March 8, 2006 Leaders Posted March 8, 2006 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.") Quote [sIGPIC]e[/sIGPIC]
*Experts* Nerseus Posted March 9, 2006 *Experts* Posted March 9, 2006 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 Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.