.NET Generic List <T> Problem, works by design, needs work. Add value instead of link

I have List<T>

and need to avoid the behavior I am about to describe:

    // assume cls and numberToAdd are parameters passed in.
    int pos = numberToAdd;
    List<MyClass> objs = new List<MyClass>(numberToAdd);

    for(int i = 0; i < numberToAdd; i++)
    {
        objs.Add(cls);
        objs[i].X = -((pos * cls.Width) + cls.Width / 2);
        pos--;
    }

    Console.WriteLine(objs[0].X + "\r\n" + objs[1].X);

      

This causes this script to print the same value.

Basically I need to change the behavior of the Add method. I would like to add a new instance of an object with the same values, not just a reference to the same object. I understand that this will use a lot more memory.

+2


source to share


5 answers


What is the 'cls' variable? Just create a new one inside each loop. What you want to do is clone it; but to be honest it will be confusing. I would suggest just creating a new one for each loop.

- Change

Notice that you will comment out "cls".



I suggest you clone it then (assuming you cannot change the call and make my suggestion above). Do this by simply creating a new one and copying all properties.

Typically, if you have control over the type 'cls', you just create the 'Copy' constructor. This is true:

class Foo {
    private int x;

    public Foo (Foo toCopy) {
       this.x = toCopy.x;
    }

    ...
}

      

+1


source


The cls extension may be required to include the clone method. The extension method will work if you cannot change the cls class.



then change objs.Add (CBS); in objs.Add (cls.Clone ());

+1


source


Oh. You need to implement cls as a struct so that it traverses value semantics.

OR you need to implement a clone method on your cls object so that you can create a method to clone the object and thus create a new reference for it so you can do this.

Even if you don't have access to the object itself, you can create an extension method to do this.

public cls Clone(this cls)
{
    //initialise the object to clone it.
    return new cls(this.param1, this.param2,...) 
}

      

+1


source


Similar to the same object, cls gets the appended number to add to the list.

You need to create a new instance of your objects inside the loop.

for(int i = 0; i < numberToAdd; i++)
{
    MyClass c=new MyClass(...);
    c.X = -((pos * c.Width) + c.Width / 2);
    objs.Add(c);
    pos--;
}

      

0


source


Have MyClass Implement ICloneable and then just use

objs.Add((MyClass)cls.Clone());

      

0


source







All Articles