Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Index out of range in a better way

Tags:

c#

My code was giving me Index out of Range exception for a certain input. Below is the problematic code:

string[] snippetElements = magic_string.Split('^');

string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";

For that particular input, array snippetElements had only one element in it, hence while trying to index 10th and 11th element, I got the exception.

For now, I have introduced the following check:

if (snippetElements.Length >= 11)
{
    string a = snippetElements[10] == null ? "" : "hello"; 
    string b = snippetElements[11] == null ? "" : "world";
}

Can someone suggest a better way to write this check. Somehow the number 11 is not looking good in the code.

like image 496
futurenext110 Avatar asked Dec 16 '22 14:12

futurenext110


1 Answers

Yes this is an old post, but still helpful. You could use this which I think is cleaner:

string a = snippetElements.ElementAtOrDefault(10) ?? "hello"; 
string b = snippetElements.ElementAtOrDefault(11) ?? "world";
like image 81
George Feakes Avatar answered Jan 06 '23 19:01

George Feakes