ElementAt() and ElementAtOrDefault() are both used to retrieve the element at a specific index in a collection, but they handle out-of-range indexes differently.
ElementAt()
Returns the element at the specified index.
Throws an exception (ArgumentOutOfRangeException) if the index is out of range.
Example (Retrieving an Element by Index)
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int element = numbers.ElementAt(2); // Gets the 3rd element (index starts at 0)
Console.WriteLine("Element at index 2: " + element);
// Output: Element at index 2: 30
// Below code return out of range an error
List<int> numbers2 = new List<int> { 10, 20, 30 };
int element2 = numbers2.ElementAt(5); // Index 5 is out of range
// Throws: ArgumentOutOfRangeException: "Index was out of range"
}
}
ElementAtOrDefault()
Returns the element at the specified index.
If the index is out of range, it returns the default value (null for reference types,
0 for numeric types, false for bool).
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int element = numbers.ElementAtOrDefault(2);
Console.WriteLine("Element at index 2: " + element);
// Output: Element at index 2: 30
int outOfRangeElement = numbers.ElementAtOrDefault(5);
Console.WriteLine("Element at index 5: " + outOfRangeElement);
// Output: Element at index 5: 0 (default for int)
// for string type
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
string result = names.ElementAtOrDefault(4);
Console.WriteLine(result == null ? "No element found" : result);
// Output: No element found (since index 4 is out of range)
}
}
When to use what?
When you are sure the index exists, use ElementAt().
When the index is out of range, use ElementAtOrDefault() to prevent exceptions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
ElementAt() vs ElementAtOrDefault() in LINQ (C#)
ElementAt() and ElementAtOrDefault() are both used to retrieve the element at a specific index in a collection, but they handle out-of-range indexes differently.
ElementAt()
Example (Retrieving an Element by Index)
ElementAtOrDefault()
nullfor reference types,0for numeric types,falsefor bool).When to use what?
ElementAt().ElementAtOrDefault()to prevent exceptions.Also, Read: What are LINQ Last(), and LastOrDefault() functions?