Followers 0

# Why am I getting this IndexOutOfRangeException?

## 5 posts in this topic

Hi, this is my code.
public Matrix GetCol (int col)
{
if (col > this.Cols)
{
throw new System.Exception("Can't get column #" + col
+ " because it's greater than the number of columns " + this.Cols
+ ".");
}

double [,] newMatrix = new double[this.Rows, 1];

for (int row = 0; 0 < this.Rows; row++)
{
newMatrix[row, 0] =  // HERE!!!!
this.matrix[row, col];
}

return new Matrix(newMatrix);
}
I traced my code and on the line indicated, I get an System.IndexOutOfRangeException. This... makes zero sense. This is a single-threaded application and this.Rows is not being modified. So why is there an exception in there? Edited by ysg
0

##### Share on other sites
The weird thing, is that while I'm tracing the code, when row is being incremented and it becomes 4, it _still_ goes into the loop and then tries to go to newMatrix[4, 0], which makes sense that I'm getting the exception.

But what doesn't make ANY sense is the fact that it's getting into the loop body after row is equal to 4. At that point, the loop should have stopped long ago.

Never mind, 0 < this.Rows is just stupid . Edited by ysg
0

##### Share on other sites

Um... "0 < this.Rows"??? That should be "row < this.Rows".

edit -- tooo slooooow

Edited by Dave Hunt
1

##### Share on other sites

Um... "0 < this.Rows"??? That should be "row < this.Rows".

edit -- tooo slooooow

Yeah .
0

##### Share on other sites

Also, if you're using zero-based arrays then you need to check that col >= this.cols at the top, as if cols = 1, the max offset you can use is actually zero.

1

## Create an account

Register a new account