Search code examples
c#arraysindexoutofboundsexception

error of my code"System.IndexOutOfRangeException"


I got this error in run time. If you can explain that is great help for me to do my coding. Thank you.

public int timePeriodInSeconds(String timeInFormat)
    {
        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeInFormat= " + timeInFormat);
        String[] timeFactors = timeInFormat.Split(':');
        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeFactors[0]" + timeFactors[0]);
        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeFactors[1]" + timeFactors[1]);
        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds timeFactors[2]" + timeFactors[2]);

        int hours = Convert.ToInt32(timeFactors[0]);
        int minutes = Convert.ToInt32(timeFactors[1]);
        int seconds = Convert.ToInt32(timeFactors[2]);

        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds hours" + hours);
        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds minutes" + minutes);
        System.Diagnostics.Debug.WriteLine("timePeriodInSeconds seconds" + seconds);

        return (hours * 60 * 60 + minutes * 60 + seconds);

    }

Solution

  • This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.

    Given an array declared as:

    byte[] array = new byte[4];
    

    You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.