Alex Rivera | Logout

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

Asked 2009-06-05T18:13:04.313
16

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?

Edit
Report

1 Answer

3

Yes, you're not cloning the object. The object is being added to both lists originally by reference, and then subsequently you're assigned a reference in the list to the new object you're creating.

That is definitely the expected result.

answered 2009-06-05T18:15:36.150

Your Answer