Reputation: 1631
Let's assume I have an object added to list on creation, does it create a copy of the object in a list or does it create new object, please consider the following code:
var obj = new A();
obj.Prop = 10;
var list = new List<A>() { obj };
foreach (var l in list) {
l.Prop = 20;
}
Console.WriteLine(obj.Prop);
What will be printed out to console?
Upvotes: 2
Views: 3482
Reputation: 9804
The answer is yes and & no.
The list will contain a copy - but of the reference. So it will point to the same object in memory. Unless you assign a reference to a different object or null at any of those variables, they will continue to point to the same thing.
To avoid this, you usually have to go into cloning. Unlike Java there is no Framework function for it.
There are two cases where you do not need to clone:
Builtin Primitive types have their value copied to a new place in memory.*
String in turn is inmutable by design. It is a rare property for a class, as you would be hard pressed to even find a dozen Inmutables in the entire .NET Framework. But in user defined classes it can be a lot more likely.
For self-made structs, you are even encouraged to make the immutable too.
*Unless the JiT and compiler Optimisations decide that it seems underused and thus can be cut out.
Upvotes: 3
Reputation: 62488
does it create a copy of the object in a list or does it create new object
As you are talking about reference types, the object is the same one, just a reference is made to it and if you change the state of the object somehow, it will reflect in the list as well, as both are pointing to the same object.
obj
and the item added in the list new List<A>() { obj };
are both pointing to the same memory location as it's a reference type. So, no new object is actually created. A copy of reference is created and both are holding reference to the same one.
Upvotes: 0