0

I'm coding on an online IDE that doesn't expose either the program input nor the stdout output, in this particular case (input too big).

Considering file to be an arbitrary string:

if (!string.IsNullOrEmpty(file))
{
    string[] splitted = file.Split('.');
    if (splitted.Length > 0)
    {
        string Test = splitted[1];
    }
}

How is it possible that the code above returns this error:

UNHANDLED EXCEPTION: System.IndexOutOfRangeException: ~message masked~ 
  at Solution.Solution.Main (System.String[] args) [0x000e4] in solution.cs:6

Line number is always wherever I try to access splitted[1]. This doesn't make any sense: if splitted.Length > 0 then splitted[1] exists.

Is this a bug of the online IDE? Or is there any condition in which a C# string[] can be of Lenght>0 and throw IndexOutOfRangeException while reading it's value at [1]?

1
  • 1
    If the Length is 1, then splitted will have a single element, accessible with the expression splitted[0]. Therefore splitted[1] may use an index that is out of range. Commented Aug 1, 2019 at 17:35

4 Answers 4

6

You're checking if the array is longer than 0, then trying to reference the second element within the array. If the length is 1, that's an error.

If you always need the second element, check that the array has at least two elements:

if (splitted.Length > 1)

Alternatively, if you're trying to access the first element:

string Test = splitted[0];
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my god... I'm so stupid. Somehow it didn't cross my mind that Length of a split will always be >0. Thanks.
@Saturnix "There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors."
0

In c#, array indexing starts at 0. It looks like in the line of code string Test = splitted[1]; that you're trying to access the first element in splitted, but since indexing starts at 0, the element in index 1 will be the second.

You want to change this to string Test = splitted[0];

Comments

0

Arrays in C# always begins indexing with 0. You should try splitted[0]

Comments

0

C# uses zero based index. Splitted[0] is guaranteed to exist in your conditional as that is the first element in the array. Splitted [1] is the second element in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.