Reputation: 87
Is it possible to make new rectangle variable with one for loop ? or should i declare it one by one ? I try to make snake and ladder map and it will be much easier if i can declare 100 rectangle with only one for loop.
I tried to make the code but it's not working.
for (int i = 0; i < 100; i++)
{
Rectangle String.Format("Land {}", i) = new Rectangle(0, 0, 200, 100);
}
Upvotes: 0
Views: 205
Reputation: 59410
You probably want an array:
var rectangles = new Rectangle[100];
for (int i = 0; i < 100; i++)
{
rectangles[i] = new Rectangle(0, 0, 200, 100);
}
An array can hold many objects and you have only one name + a number to access it.
For a square, you can do something like
var rectangles = new Rectangle[100];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
rectangles[i*10 + j] = new Rectangle(i*100, j*100, 100, 100);
}
}
Even cooler, there's a 2D version of an array:
var rectangles = new Rectangle[10,10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
rectangles[i, j] = new Rectangle(i*100, j*100, 100, 100);
}
}
Don't forget to add the rectangles to your Form in order to display it.
When you understood the concept of an array, you might want to have a look at Lists and then Dictionaries. They are more flexible, because they don't have a fixed size.
Upvotes: 1