Safe element of array access
Question
What is the safe method to access an array element, without throwing IndexOutOfRangeException
, something like TryParse
, TryRead
, using extension methods or LINQ?
Solution
You could use the following extension method.
public static 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) ) {
...
}
OTHER TIPS
Use the System.Linq ElementAtOrDefault method. It handles an out-of-range access without throwing an exception. It returns a default value in the case of an invalid index.
int[] array = { 4, 5, 6 };
int a = array.ElementAtOrDefault(0); // output: 4
int b = array.ElementAtOrDefault(1); // output: 5
int c = array.ElementAtOrDefault(-1); // output: 0
int d = array.ElementAtOrDefault(1000); // output: 0
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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow