IndexOutOfRangeException on a multidimensional array despite using GetLength check
I am using the following code to read values ββfrom an Excel spreadsheet:
// Start with passed
int lastPassRow = sheets[passedVehicles].GetLength(0);
for (int i = 1; i < lastPassRow; i++)
{
// Exception here
if(DateTime.TryParse(sheets[passedVehicles][i, 0].ToString(), out result))
{
passedDates.Add((DateTime)sheets[passedVehicles][i, 0]);
}
}
The type sheets[passedVehicles]
is a multidimensional array Object[,]
and the for loop above gives me an exception IndexOutOfRange
at i = 1, even though I am checking the number of lines.
I added some logs for the spreadsheet in question and confirmed:
- i = 1 - iteration that fails
- The value
lastPassRow
is 4 - The value is
sheets[passedVehicles].GetLength(1)
also 4.
All values ββturn out to be in range for me. Is there something else that might cause this exception?
Note. I am starting with i = 1 because row 0 is the header in the spreadsheet and does not contain the data I am trying to read.
+2
source to share