-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,496
  • 3
  • 36
  • 68
codein
  • 317
  • 2
  • 12
  • 2
    check the value of Months.Length at debug – Tharif Apr 11 '15 at 05:44
  • The [Length property](https://msdn.microsoft.com/en-us/library/system.array.length.aspx) returns *the total number of elements in all the dimensions of the Array* – stuartd Apr 11 '15 at 11:25

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,960
  • 1
  • 16
  • 25