Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe element of array access

What is the safe method to access an array element, without throwing IndexOutOfRangeException, something like TryParse, TryRead, using extension methods or LINQ?

like image 617
abatishchev Avatar asked Nov 18 '25 17:11

abatishchev


1 Answers

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

like image 144
stomy Avatar answered Nov 20 '25 07:11

stomy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!