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?

1
  • I'm pretty sure you're doing something wrong, what about some piece of code? Commented Feb 17, 2009 at 23:39

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I thought something like that was happening! Thanks a lot for your answer, you saved me a lot of aggravation.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.