Jump to content
Xtreme .Net Talk

Recommended Posts

  • *Experts*
Posted

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

"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
Posted

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....

~Nate�

___________________________________________

Please use the [vb]/[cs] tags on posted code.

Please post solutions you find somewhere else.

Follow me on Twitter here.

  • Leaders
Posted
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.")
[sIGPIC]e[/sIGPIC]
  • *Experts*
Posted

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

"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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...