Advantage of Immutable String in C# programming

(Last Updated On: February 26, 2019)

Advantage of immutable string in C# programming is data security. Let’s understand benefits of immutable string with a C# program example.

Recommended to read immutable and mutable string in C# program.

Here is the scenario,

  • Main() program has a String msg = “Hello World”; and will call Display1()and then Display2()method.
  • Display1()method will read the string and will modify the string to “My World”.
  • Display2() method must read the original “Hello World” string and not the string modified by Display1() method.

Since, C# string is immutable that is it cannot be modified, hence, string modified by Display1() method will not be reflected in main() function. And Display2() method will read the original string.

Hence, original data is safe!!!

So, conclusion is that if we pass a string to some method  for read and use only, the method will not be able to modify the original string because of its immutability. Even though string is changed in the method body. So,if original string is used somewhere in the program that will get expected string value.

C# Program Example – advantage of immutable string



Hello World
My World
Hello World
Hello World