views:

902

answers:

2

I have a small program where I have been trying to create collections of a particular object I have created (Job).

Regardless of whether I am using an array, collection or list, each time I add a new instance of the object to the array/collection/list, it overwrites all previous items with the same object.

For example, let's say Job has only one property, name. If I were to have Jobs with names 1,2,3,4 in a collection, each time I add the individual job, all previous jobs get the name of the current job. So by the time I add job 4, all the jobs have the name of 4.

Has anyone experienced this issue before?

A: 

I suspect you are adding the same instance multiple times - i.e. (I'll use C# here...)

Job job = new Job();
job.Name = "a";
list.Add(job);
job.Name = "b";
list.Add(job);

What you have done is add 2 references to the same object to the list. What you should have done was:

Job job = new Job();
job.Name = "a";
list.Add(job);
job = new Job(); /// <<===== here
job.Name = "b";
list.Add(job);

This is because classes are reference-types; all you are adding is a reference. Structs are value-types, and would work like you expect, except that unless you really know what you are doing, structs should be immutable (i.e. no editable properties once created).

Marc Gravell
I thought something like that was happening! Thanks a lot for your answer, you saved me a lot of aggravation.
S N
A: 

It would sound as if your were reusing the Job object variable after adding it to the list, without recreating the Job object. All items in the list will point to this object.

baretta