Bedouin Bedouin - 1 month ago 8
C# Question

An unhandled exception of type System.IndexOutOfRangeException eroror in C#?

I get error when I try to fill array:


An unhandled exception of type 'System.IndexOutOfRangeException'


The array initialization:
private int[,] imageMatrix = new int[320, 240];


And variables:

private int widthOutImage = 320;
private int heightOutImage = 240;


Loop that fills array:

for (int i = 1; i <= widthOutImage; i++)
{
for (int j = 1; j <= heightOutImage; j++)
{
imageMatrix[i, j] = 0;
}
}

Answer

Array index start with 0 and end with less than one of its length. In your case you are starting from 1 which left 0 and end is the length which over the range of it, So you need to make it

for (int i = 0; i < widthOutImage; i++)
{
      for (int j = 0; j < heightOutImage; j++)
      {
         imageMatrix[i, j] = 0;
      }
 }
Comments