Search code examples
c#listreference-type

C# Does list hold a reference to the element after adding it or creates a copy?


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?


Solution

  • 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:

    1. Builtin Primitive types
    2. The buildin string type (despite being a reference type)

    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.