C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: On out-of-range accesses, ElementAtOrDefault returns the default value for the type, which for int is 0.
DefaultC# program that uses ElementAtOrDefault
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
And: This could be useful if a collection is queried for invalid indexes, and actual stored values are not necessary for the algorithm.
To start: This program uses an array of three string literal elements. Arrays are IEnumerable collections.
ArrayIEnumerableAnd: We can index this array through the ElementAt method in the System.Linq namespace.
Warning: The method call with argument 3 throws a System.ArgumentOutOfRangeException.
ArgumentExceptionC# program that uses ElementAt method
using System;
using System.Linq;
class Program
{
static void Main()
{
// Input array.
string[] array = { "Dot", "Net", "Perls" };
// Test ElementAt for 0, 1, 2.
string a = array.ElementAt(0);
Console.WriteLine(a);
string b = array.ElementAt(1);
Console.WriteLine(b);
string c = array.ElementAt(2);
Console.WriteLine(c);
// This is out of range.
string d = array.ElementAt(3);
}
}
Output
Dot
Net
Perls
Unhandled Exception: System.ArgumentOutOfRangeException:
Index was out of range.