How can I create a new Rectangle without setting a name?

255 views Asked by At

for my new project I want my code to create a new rectangle for each one existing in a list.

Given is the List "particles". I want to do something like

foreach(Rectangle rec in particles){
Rectangle r2 = new Rectangle(10, 10, 10, 10);
particles.add(r2);
}

The problem is, that I need to define a name. If I don't know, how many rectangles will be in list particles when the code executes, I can't just do it like that (I hope you get what I mean). What I need is something like a function that creates a new rectangle with the name r3 or r4 or r5 (...) as long as there are new rectangles. I really don't know how. Can you help me?

3

There are 3 answers

0
Idle_Mind On

Here's an example of using a Dictionary, as suggested by MiiinimalLogic:

    private Dictionary<string, Rectangle> pRecs = new Dictionary<string, Rectangle>();

    private void button1_Click(object sender, EventArgs e)
    {
        List<Rectangle> particles = new List<Rectangle>();
        // ... assuming there are some values in "particles" ...

        for (int i = 0; i < particles.Count; i++ )
        {
            // you can't have duplicate keys, make sure "pRecs" is empty if you are re-using it!
            pRecs.Add("r" + i.ToString(), new Rectangle(10, 10, 10, 10));
        }
    }

    private void Foo()
    {
        // ... access one of the rectangles "by name" from somewhere else ...
        Rectangle tmp = pRecs["r2"];
    }
2
Vikas On

for my new project I want my code to create a new rectangle for each one existing in a list.

Your existing code will not work as you're trying to modify the list while iterating it.

  1. If you need a new list like particles list, you can do like this

    var newParticles = new List<Rectangle>();    
    foreach(Rectangle rec in particles)
    {
        Rectangle r = new Rectangle(10, 10, 10, 10);
        newParticles.add(r);
    }
    
  2. If you need new rectangles created in the particles list then create new object (say Particle) and define 2 properties like ExistingParticle, NewParticle, then

    foreach(Rectangle rec in particles)
    {
        Rectangle r = new Rectangle(10, 10, 10, 10);
        rec.NewParticle=r;
    }
    
0
MiiinimalLogic On

You don't have to increment the variable name, you just need to add the rectangles as you are to the collection and then the index becomes the reference. i.e particles.get(0) will be your r0 rectangle and so on.

If you absolutely need a 'plain english' reference, use a map and set the key as a String such as "r"+indexNumber i.e r0, r1, r2..etc. Then the value for that key is the actual rectangle object you created in that loop.