10 May 2015

why string are called immutable in c#

You have often heard strings are immutable and if you are wondering why "strings are called immutable", then you are reading the right article on this page.

Immutable in English means, "unchangeable" and it has the same meaning in c#.net well.

string loan1 ="Housing Loan";
string loan2 = loan1;

// Update the string value
loan1 =loan1+ " And loan to buy car";

After assigning a new value to the string variable 'loan1', the reference where it points to has been changed. This is demonstrated by making use of address(&) operator in Visual Studio Quick Watch window.

C#.NET program showing why strings are called immutable

With each string value update, string variable address is changing. This means the original "string" value is not getting updated with each update, instead, a new string is being created and the new address is assigned to the string variable. This is why strings are called immutable.

No comments:

Post a Comment