user2246303
user2246303

Reputation: 27

C# issue with list .add()

I have a class:

ProductData ProductData = new ProductData(); 

and created a list:

List<ProductData> ProductDataList = new List<ProductData>();

when I add items to the list as so:

ProductDataList.Add(ProductData);

the last element in the list is overwriting all previous elements, I am not sure why this is happening, can anyone help?

here is more of the structure:

ProductData ProductData = new ProductData();

List<ProductData> ProductDataList = new List<ProductData>();

while (myReader.Read())
                {
                    ProductData.value = “some values I am assigning go here”;

          ProductDataList.Add(ProductData);
       };

Upvotes: 1

Views: 487

Answers (2)

Andre Calil
Andre Calil

Reputation: 7692

I bet that your full code must be something like this:

ProductData ProductData = new ProductData(); 
ProductData.Something = "1st";

ProductDataList.Add(ProductData);

ProductData.Something = "1st";

ProductDataList.Add(ProductData);

ProductData.Something = "2nd";

ProductDataList.Add(ProductData);

ProductData.Something = "3rd";

ProductDataList.Add(ProductData);

And you say that it's overwriting because all of them have the value of "3rd". It's not an issue with the list, it's with your object instance.

Note that you've created only one instance, it's that new ProductData over there. When you change it, you're not creating new instances, but simply changing your only instance.

You should create new instances for each object you have.

Upvotes: 1

Servy
Servy

Reputation: 203814

You're not creating multiple new ProductData instances, instead your mutating the same instance over and over again.

You almost certainly want to just move the line: ProductData ProductData = new ProductData(); from outside of your loop to inside of it. That will ensure that you create N instances, not one.

Upvotes: 9

Related Questions