Alex Rivera | Logout

if strings are immutable in c#, how come I am doing this?

Asked 2011-08-03T02:43:30.970
10

I read today, in c# strings are immutable, like once created they cant be changed, so how come below code works

string str="a";
str +="b";
str +="c";
str +="d";
str +="e";

console.write(str) //output: abcde

How come the value of variable changed??

c#
Edit
Report

1 Answer

18

String objects are immutable, but variables can be reassigned.

You created separate objects

a
ab
abc
abcd
abcde

Each of these immutable strings was assigned, in turn, to the variable str.

You can not change the contents (characters inside) a string.

Changing the variable is a different thing altogether.

answered 2011-08-03T02:46:01.143

Your Answer