Saturnix
Saturnix

Reputation: 10564

IndexOutOfRangeException with array.Length>0 while reading array[1]

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]?

Upvotes: 0

Views: 74

Answers (4)

LadderLogic
LadderLogic

Reputation: 1140

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.

Upvotes: 0

David
David

Reputation: 218847

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];

Upvotes: 6

Hitesh Kacholiya
Hitesh Kacholiya

Reputation: 38

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

Upvotes: 0

JamieT
JamieT

Reputation: 1187

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];

Upvotes: 0

Related Questions