What is the safe method to access an array element, without throwing IndexOutOfRangeException
, something like TryParse
, TryRead
, using extension methods or LINQ?
views:
116answers:
2
+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
2009-03-28 19:22:56
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
2009-03-28 22:27:31
@Jim, that's what I get for posting before I had my coffee finished. Fixed the typos
JaredPar
2009-03-28 22:32:42
Might also want to check that index >= 0.
Jim Mischel
2009-03-28 23:37:15
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
2009-03-28 19:46:22
No, I read command line argument and have to ensure next argument existence without throwing an exception (without loop exit)
abatishchev
2009-03-28 19:51:53