Tuesday, 15 May 2012

c# - How to handle Index out of range in a better way -



c# - How to handle Index out of range in a better way -

my code giving me index out of range exception input. below problematic code:

string[] snippetelements = magic_string.split('^'); string = snippetelements[10] == null ? "" : "hello"; string b = snippetelements[11] == null ? "" : "world";

for particular input, array snippetelements had 1 element in it, hence while trying index 10th , 11th element, got exception.

for now, have introduced next check:

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

can suggest improve way write check. somehow number 11 not looking in code.

can suggest improve way write check. somehow number 11 not looking in code.

well accessing element 11 index, if have index in variable can utilize in check, otherwise 11 fine in check. check should if(index < snippetelements.length)

something like:

int index = 11; if(index < snippetelements.length) { string b = snippetelements[index] == null ? "" : "world"; }

c#

No comments:

Post a Comment