Reputation: 908
I have a program that generates a grid of buttons and i want to store these buttons in an nested array list but the way I am doing does not seem to be correct
This is my code:
List<List<Button>> buttonsList = new List<List<Button>>();
List<Button[]> rowList = new List<Button[]>();
//Some method that creates a grid of buttons
buttons = new Button[row][];
for (int r = 0; r < row; r++)
{
buttons[r] = new Button[col];
buttonsList.Add(rowList[r]);
for (int c = 0; c < col; c++)
{
buttons[r][c] = new Button();
rowList[c].Add(buttons[r][c]);
}
}
Upvotes: 0
Views: 728
Reputation: 126854
First thing you need to understand is that a List<T>
and a T[]
are not equivalent* (*see footnote). Your code seems to want to treat a list as an array, and that's just not going to work.
A List<List<Button>>
can be used in the following manner:
var listOfLists = new List<List<Button>>();
var listOfButtons = new List<Button>();
listOfButtons.Add(new Button());
listOfLists.Add(listOfButtons);
And you can continue to add buttons to the button list, create more button lists, add buttons to those, and add all of them to the list of lists and you can do all of this in a loop or nested loops.
An array Button[][]
is treated differently. It's not dynamically sized, and would be used in a different manner.
var arrayOfArrays = new Button[10][];
var arrayOfButtons = new Button[3];
arrayOfButtons[0] = new Button();
arrayOfButtons[1] = new Button();
arrayOfButtons[2] = new Button();
arrayOfArrays[0] = arrayOfButtons;
And then you still have 9 more arrays of buttons you could set (in this example).
Your code attempts to add an array of buttons to a list expecting a list of buttons. And there are a few other items to sort through, but the basic idea is that you are mixing up these two different collections, and the compiler is loudly complaining.
To fix your code, begin by employing the proper types for what you need to do, and then consistently and correctly use those types in your logic.
As a starter, see how far you get with these snippets.
// using List<List<Button>>
var buttonLists = new List<List<Button>>();
for (int r = 0; r < row; r++)
{
var buttonRow = new List<Button>();
buttonLists.Add(buttonRow);
for (int c = 0; c < col; c++)
{
buttonRow.Add(new Button());
}
}
// using Button[][]
var buttonArrays = new Button[row][];
for (int r = 0; r < row; r++)
{
buttonArrays[r] = new Button[col];
for (int c = 0; c < col; c++)
{
buttonArrays[r][c] = new Button();
}
}
*Unless you are referencing them via a common interface type, in which case they still aren't equivalent but are compatible, but that is beyond the scope of this answer and not particularly useful in this context, given the code snippets involved.
Upvotes: 3