-5

I am trying to do this array in C# WPF. On this part of the code:

buttons[1, 0] = button2x1;

It throws :

System.IndexOutOfRangeException error.

But I don´t think that is out of range. What is going on?

        buttons = new Button[2, 2];

        buttons[0, 0] = button1x1;
        buttons[0, 1] = button1x2;
        buttons[0, 2] = button1x3;
        buttons[1, 0] = button2x1;
        buttons[1, 1] = button2x2;
        buttons[1, 2] = button2x3;
        buttons[2, 0] = button3x1;
        buttons[2, 1] = button3x2;
        buttons[2, 2] = button3x3;
Abdellah OUMGHAR
  • 3,627
  • 1
  • 11
  • 16
Marinaro
  • 37
  • 1
  • 10
  • 5
    The `2` that you have defined is the count. Meaning that you can only go up to index `1` – Matt Rowland May 06 '16 at 17:57
  • 3
    Possible duplicate of [What is IndexOutOfRangeException and how do I fix it?](http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it) – Matt Rowland May 06 '16 at 17:58
  • 2
    Error actually happens here `buttons[0, 2] = button1x3;` `2` **is** out of range – adjan May 06 '16 at 17:59

3 Answers3

3

Arrays (in C#) are zero index based i.e. your 1st element will be at index 0, 2nd at 1 and so on. When you declare an array, the number you provide during the declaration (the 2s in new Button[2,2]) are the number of elements the array can hold. Considering the fact that it is 0 based index, your highest possible index is declared number of elements - 1. Please refer to msdn documentation @here for more info on arrays.

In your case, when you do buttons[0, 2] = button1x3;-- you are trying to access out of range index, hence the error (please note that you have 4 other statements in your code snippet that will cause this error). If you need to do so, change your declaration to hold 3 elements instead of 2.

var buttons = new Button[3,3];
haku
  • 4,105
  • 7
  • 38
  • 63
1

Remember that access to arrays is through zero-based index, therefore you can not access index 2 but only 0,1

taquion
  • 2,667
  • 2
  • 18
  • 29
1

As you created an array of 2 indexes, it only allows you to use two: 0 and 1

You must remember, the index 0 count as 1 either.

To do what you want you need:

buttons = new Button[3, 3];

buttons[0, 0] = button1x1;
buttons[0, 1] = button1x2;
buttons[0, 2] = button1x3;
buttons[1, 0] = button2x1;
buttons[1, 1] = button2x2;
buttons[1, 2] = button2x3;
buttons[2, 0] = button3x1;
buttons[2, 1] = button3x2;
buttons[2, 2] = button3x3;

Being 3 indexes, 0, 1 and 2.

Luis G. Lino
  • 163
  • 12