Copy Constructor to load List<T>

G

Guest

In VS2003 I have been using an ArrayList loading it with a copy constructor
and it seems to work fine. {I am acutally loading a lot of constants first,
not one a shown}

public ArrayList al;
....
MyClass mc = new MyClass()
mc.a = 1;
loop...
{
mc.b = loopcount;
al.Add((object)(new MyClass(mc)));
}

With VS2005 I decided to change it to to generics List, but this made all of
the items in the list the same (takes on the last MyClass loaded values).
public List<MyClass> al;
....
MyClass mc = new MyClass()
mc.a = 1;
loop...
{
mc.b = loopcount;
al.Add(new MyClass(mc));
}
So I tweeked it to create a new mc each time in the loop which works, but it
would seem the other should work too.
public List<MyClass> al;
....
loop...
{
MyClass mc = new MyClass()
mc.a = 1;
mc.b = loopcount;
al.Add(new MyClass(mc));
}
It seems the new and copy constructor isn't making a new object. As I am a
copy constructor junkie this worries me.
 
N

Nicholas Paldino [.NET/C# MVP]

GRiN,

The second loop is excessive. Since you are creating a new instance
every time, there is no need to use the extra copy constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top