views:

116

answers:

2

What is the safe method to access an array element, without throwing IndexOutOfRangeException, something like TryParse, TryRead, using extension methods or LINQ?

+3  A: 

You could use the following extension method.

public bool TryGetElement<T>(this T[] array, int index, out T element) {
  if ( index < array.Length ) {
    element = array[index];
    return true;
  }
  element = default(T);
  return false;
}

Example:

int[] array = GetSomeArray();
int value;
if ( array.TryGetElement(5, out value) ) { 
  ...
}
JaredPar
You should change array[i] to array[index]. Also, I think your logic is backwards. If array.Length <= index, then trying to access array[index] is going to throw an exception.
Jim Mischel
@Jim, that's what I get for posting before I had my coffee finished. Fixed the typos
JaredPar
Might also want to check that index >= 0.
Jim Mischel
A: 

If you want to loop through the elements in the array safely, just use an enumerator:

foreach (int item in theArray) {
   // use the item variable to access the element
}
Guffa
No, I read command line argument and have to ensure next argument existence without throwing an exception (without loop exit)
abatishchev