
You want to access an element in a collection and never have an exception thrown if the element is out of range. With ElementAtOrDefault in the C# language and the System.Linq namespace, we can access any index safely.
In this program we create a three-element array; the only valid indexes to access are 0, 1 and 2. We show how ElementAtOrDefault works on valid indexes, and also out-of-range indexes. On out-of-range accesses, it returns the default value for the type, which for int is 0.
DefaultThis C# page looks at the usage of the ElementAtOrDefault method. ElementAtOrDefault is found in System.Linq.
Program that uses ElementAtOrDefault [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 4, 5, 6 };
int a = array.ElementAtOrDefault(0);
int b = array.ElementAtOrDefault(1);
int c = array.ElementAtOrDefault(-1);
int d = array.ElementAtOrDefault(1000);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
}
}
Output
4
5
0
0
Conceptually, ElementAtOrDefault can make a collection be infinite, with every possible index returning a valid value—the default value—if it is not actually present in memory. This could be useful in situations where a collection is queried for invalid indexes, and actual stored values are not necessary for the algorithm to proceed.
We looked at how ElementAtOrDefault can transform how you access collections. This method eliminates the need for bounds-checking, but it could create extra complexity down the road if you need to add special casing for the default value. Often, explicitly checking bounds is an easier approach.
LINQ Examples