Ramesh
Ramesh

Reputation: 1752

Problem with List<T> object

List<Person> allPersons= ReadallPersons()

Person aPerson=allPersons[0];

aPerson.Name="test1";

allPersons.Add(aPerson)

allPersons has one single person object, I am assigning that person object into 'aPerson' object.Just Renaming the person name as 'test1' and again adding it to the list.

Now if we check the list, both person's object's Name has assigned as 'test1'.

What is the problem in this?

How can we sort out this?

Upvotes: 0

Views: 77

Answers (5)

Bhaskar
Bhaskar

Reputation: 10681

Person aPerson=allPersons[0] copies just the reference of the item in the List.

You will need to use 'new' to create a new instance of the object, otherwise it actually copying the pointer and any change would effect just one object.

List allPersons= ReadallPersons()

**Person aPerson= new Person();**

aPerson.Name='test1'

allPersons.Add(aPerson)

or you can perform a DeepCopy of the object, see How do you do a deep copy of an object in .NET (C# specifically)?.

Upvotes: 0

Jon Grant
Jon Grant

Reputation: 11530

When you do...

Person aPerson = allPersons[0];

...you are obtaining a reference to the first person object in the list, i.e. it is the exact same item, not a copy.

See the top answer to this question for how to make a copy.

Upvotes: 0

Shirik
Shirik

Reputation: 3701

The list stores references, not copies of objects. As a result, when you modify the name of the object and change it, you're changing both the one in the list and the one you stored in aPerson, because it is the same object.

To create a new object, you need to use the new operator and create a new Person object, then add it to the list.

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44595

You are always working with the same object, you add it to the list, take it out, modify it, add it again in second position...

classes are reference types so no matter in how many variables you put it all those vars always reference the same object in memory and you change it from somewhere and all references see the same updated data.

Upvotes: 2

Emond
Emond

Reputation: 50672

You need to make a copy of the object. You are only copying the reference to the same object. So both entries point to the same Person.

If Person implements IClonable you could call Clone(), modify the clone and add it to the list.

Upvotes: 7

Related Questions