What is the safe method to access an array element, without throwing IndexOutOfRangeException, something like TryParse, TryRead, using extension methods or LINQ?
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
See Also: DotNetPearls - ElementAt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With