Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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??

like image 351
Rusi Nova Avatar asked Aug 03 '11 02:08

Rusi Nova


1 Answers

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.

like image 198
Ray Toal Avatar answered Oct 14 '22 04:10

Ray Toal