Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: When adding the same object to two List<object> variables, is the object cloned in the process?

Tags:

c#

collections

I have something similar to this:

// Declarations:
List<SomeType> list1 = new List<SomeType>();
List<SomeType> list2 = new List<SomeType>();

...

SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);

...

list1[indexOfSomething] = new SomeType("SomeOtherName");

And the object in list2 isn't changed... Is that the expected result?

like image 518
Austin Hanson Avatar asked Jun 05 '09 18:06

Austin Hanson


2 Answers

Yes, but nothing's cloned. Before the assignment, the same object is in both lists. After the assignment, you have two unique objects in two lists.

Do This:

list1[indexOfSomething].name = "SomeOtherName";

and the object in list2 will change, too.

like image 131
Can Berk Güder Avatar answered Sep 22 '22 07:09

Can Berk Güder


// Declarations:
List<SomeType> list1 = new List<SomeType>();
List<SomeType> list2 = new List<SomeType>();

...

SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);

Remember, when you add an object to a list, you're really just adding a pointer to the object. In this case, list1 and list2 both point to the same address in memory.

list1[indexOfSomething] = new SomeType("SomeOtherName");

Now you've assigned the element list1 to a different pointer.

You're not really cloning objects themselves, you're copying the pointers which just happen to be pointing at the same object. If you need proof, do the following:

SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);

list1[someIndex].SomeProperty = "Kitty";

bool areEqual = list1[someIndex].SomeProperty == list2[someIndex].SomeProperty;

areEqual should be true. Pointers rock!

like image 40
Juliet Avatar answered Sep 23 '22 07:09

Juliet