Proof that string is immutable in C# Programming

(Last Updated On: March 23, 2018)

We know that string is immutable in C# programming and cannot be modified or changed. Read detail of mutable and immutable string in C#.

Let’s proof the string immutability with program example  and source code using object memory references.
In below C# program, first we’ll check the reference of memory of  strings s1 and s2 pointing to the same location.

string s1 = ” Hello World “; // string memory allocation

string s2 = s1;// s2 pointing to same memory allocation

if we compare the memory reference of s1 and s2, below c# code example program will output as Equal.

 

 

Now, as soon as we modify the string s2 as s2 = ” C# Programming World”; s2 will no longer point to same memory allocation but different memory will be created for it as it cannot change the existing string as it is immutable.

So, below program will output as s1 and s2 are “Not Equal”.

 

 

Conclusion is that if we try to modify the previously allocated string at the memory, it will not be modified as it is immutable, but a new memory will be created and new string will be placed in it.

One of the technical c# interview questions can be asked as what is benefits of immutable string in C# Object Oriented Programming? or Why string is immutable in C# programming.