Deepanjan Nag
Deepanjan Nag

Reputation: 921

Why does the location of the string reference itself change?

string[] names = {"avinash","harish", "savan", "shyam" };
foreach (var name in names)
    namesAll += name;

We know that string is immutable in .NET. Each time we concatenate a new string to an existing string, a new memory location is reserved which contains the new concatenated string...which is pointed to by the string reference. This seems fine to me.

What stumps me is why should the the location of the string reference (namesAll) also change? To me this seems completely unnecessary. You can ascertain this in Visual Studio using the Memory window to look at the location of the string reference (namesAll).

Here's the address of namesAll after each iteration: 0x01ef9594 0x01ef961c 0x01ef9644 Please note, this is not the address of the concatenating string (which will obviously change), but the address of the string reference namesAll.

Upvotes: 1

Views: 145

Answers (2)

Mark Synowiec
Mark Synowiec

Reputation: 5445

Garbage Collection

See the link for a full explanation, but here are the details about moving references:

"When a garbage collection is triggered, the garbage collector reclaims the memory that is occupied by dead objects. The reclaiming process compacts live objects so that they are moved together, and the dead space is removed, thereby making the heap smaller. This ensures that objects that are allocated together stay together on the managed heap, to preserve their locality."

Upvotes: 0

Oded
Oded

Reputation: 498914

A specific string will get a reference that is reused anywhere the string is used. Changing the value referenced will change all these other locations as well, hardly what you want...

As a new string is created in each iteration, a new string gets a new memory location - this is referenced by the variable, hence the new address.

Upvotes: 7

Related Questions