Advantage of Immutable String in C# programming

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#.

Here is the scenario,

  • The main() method has a String msg = “Hello World”; and will call the display1() method and then the display2() method.
  • The display1() method will read the string and modify the string to “My World”.
  • The 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, the string modified by the 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  to 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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    class Program
        static void Main(string[] args)
            String msg = "Hello World";

            //Display1 method will read the string and modify it

            //From here below program will read original
            //string i.e. "Hello World". as string is immutable
            //and cannot be changed by Display1 method.

            Console.WriteLine(msg);//print original string.
            //Display2 method will also read original string.


        //Since String is a reference type y will
        //point to the same location where msg is
        //pointing to
        //Note that value of string msg is not copied
        //But reference of msg string as String data
        //Type is reference type.
        public static void Display1(String y)
            //It will print the original string
            //Y is having the same reference as msg variable.
            //but If we try to change the  value of y 
            //it will create another memory and assign "My World"
            //string and it will not modify the memory msg variable
            //is pointing to in Main program.
            y = "My World";

        //Since String is a reference type y will
        //point to the same location where x is
        //pointing to
        private static void Display2(String y)



Hello World
My World
Hello World
Hello World

Related Posts