LINQ Interview Question #49
What does ElementAtOrDefault do?
Filtering, Projection, Ordering & Element Operators Mid-Level Intermediate
Quick Interview Answer
ElementAtOrDefault returns the element at the specified zero-based position, or the default value when the index is outside the valid range.
Detailed Explanation
ElementAtOrDefault returns the element at the specified zero-based position, or the default value when the index is outside the valid range.
It avoids an out-of-range exception, but callers should consider whether the default value can be distinguished safely from a legitimate element value.
Code Example
var names = new[] { "Ali", "Sara" };
string? third = names.ElementAtOrDefault(2);
// null