-1
string[,] Months = new string[12,2] { { "Jan", "1" }, { "Feb", "2" }, { "Mar", "3" }, { "Apr", "4" }, { "May", "5" }, { "Jun", "6" }, { "Jul", "7" }, { "Aug", "8" }, { "Sep", "9" }, { "Oct", "10" }, { "Nov", "11" }, { "Dec", "12" } };

for (int i = 0; i < Months.Length; i++)
{
    if (Convert.ToInt32(Months[i,1]) > DateTime.Now.Month)
    {
        //Do Something
    }
    else
    {
        //Another Task
    }
}

The above code throws an index out of "range exception". However, When I inserted the length of the array manually in the for loop, everything worked

for (int i = 0; i < 12; i++)
{
    if (Convert.ToInt32(Months[i,1]) > DateTime.Now.Month)
    {
        //Do Something
    }
    else
    {
        //Another Task
    }
}

What caused this exception? I have been using similar code for a long time now and no issue. Just wrote this one this morning and faced red screen.

jrtc27
  • 8,436
  • 3
  • 34
  • 68
codein
  • 307
  • 2
  • 12

2 Answers2

3
for (int i = Months.GetLowerBound(0); i <= Months.GetUpperBound(0); i++)
mathieu
  • 477
  • 3
  • 9
2
for (int i = 0; i < Months.GetLength(0); i++)

Length refers to size of all elements in array, which is 24. To get size of one dimension, use GetLength()

Phuong Nguyen
  • 2,870
  • 1
  • 13
  • 22