What is C# mutable string and immutable string?

(Last Updated On: February 26, 2019)

C# mutable string and immutable string is in fact very simple concept and will understand with example. Immutable meaning is unchanging over time or unable to be changed and mutable meaning is changeable or modifiable.

Immutable String in C#

Immutable string cannot be changed once declared and defined. In a simple word, if we declare a string for example, string str = “interview”, a memory will be allocated for it and “interview” string will be placed in the memory.

If we try to change the string pointed by str variable e.g. str = “ interview sansar”, an another new memory will be created and “interview sansar” string will be placed in it. Now, str  variable will no longer point the memory where string “interview” was placed and old memory will be destroyed by GC.

Immutable string – C# program example:


You might be thinking that if we append a string or assign a string to variable str then just another memory is getting created because of immutable properties of string and older one is getting collected by GC and destroyed, then what is the advantage of immutable string in C# programming language.

Read another interview question benefits of immutable string in CSharp.


C# mutable string

C# mutable string means a string in a memory can be changed or modified and no new memory will be created on appending a string. We can use string builder class to create a mutable strings in c# programming.

C# Code Example – Mutable string using StringBuilder class


Conclusion: Difference between immutable and mutable string in C# language is that immutable string cannot be modified and mutable string can be modified at a memory location.

NOTES: If in a C# programming, a heavy manipulation of string is happening specially within a loop, then it is better to use mutable string for better performance. Practically, I have experienced an application hang. So, we changed it to mutable string using string Builder class.