Proof that string is immutable in C# Programming

(Last Updated On: February 26, 2019)

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.

 

class ProofOfStringImmutability
{
    static void Main(string[] args)
    {
        string s1 = "Hello World";
        string s2 = s1;

        //both s1 and s2 string variable points
        //to same memory location.
        if (object.ReferenceEquals(s1, s2))
        {
            Console.WriteLine("Equal");
        }
        else
        {
            Console.WriteLine("Not 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”.

 

class ProofOfStringImmutability
{
    static void Main(string[] args)
    {
        string s1 = "Hello World";
        string s2 = s1;

        s2 = "Programming World";

        //Now, Compare if s1 and s2 is pointing to same location
        if (object.ReferenceEquals(s1, s2))
        {
            Console.WriteLine("Equal");
        }
        else
        {
            Console.WriteLine("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.