Emir
Emir

Reputation: 13

Using concatenate to redefine an already defined string

I know a string is immutable and cannot be redefined, but in this foreach loop the string is changed multiple times by adding elements of an array.

var stringOfNames = "";
var arrayOfNames = new string[5] { "jack", "marry", "joe", "jimmy", "bud" };

foreach (var item in arrayOfNames)
{
    stringOfNames += item;
    Console.WriteLine(stringOfNames);

}

Expected:

An error stating "Variable is already defined in this scope."

Actual:

The string is changed by adding the other names.

Also, what's the difference between these two:

1)

var a = "something";
var a = "something else";

2)

var a = "something";
a+= "asdf";

Why does the second option work?

Upvotes: 0

Views: 353

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500065

but in this foreach loop the string is changed

No, it's not.

The variable changes value, to refer to a different string on each iteration. Each of the string objects in question - both the original ones in the array and the intermediate results - stays with the same data that it had before.

Here's another way to demonstrate that:

string x = "ab";
string y = x;
x += "cd";

Console.WriteLine(x); // abcd
Console.WriteLine(y); // ab

Here the value of x changes to refer to a new string, but the value of y still refers to the original string, "ab".

Basically you need to be very clear about three separate concepts:

  • Variables: named storage locations which store values
  • References: one kind of value, which refers to an object.
  • The objects themselves

I have an answer on another question which may help clarify the differences.

Upvotes: 8

nlawalker
nlawalker

Reputation: 6514

stringOfNames += item; does not define the variable stringOfNames, it assigns a value to it.

Upvotes: 0

Related Questions