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?
Related Questions
No related questions found
I suspect you are adding the same instance multiple times – i.e. (I’ll use C# here…)
What you have done is add 2 references to the same object to the list. What you should have done was:
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).