What is the difference between a mutable and immutable string in C#?


Mutable string

StringBuilder is a mutable string in C#. With StringBuilder, you can expand the number of characters in the string. The string cannot be changed once it is created, but StringBuilder can be expanded. It does not create a new object in the memory.

Set StringBuilder −

StringBuilder str = new StringBuilder();

Let us see an example to learn how to work with StringBuilder in C# −

Example

 Live Demo

using System;
using System.Text;

public class Program {
   public static void Main() {
      StringBuilder str = new StringBuilder("Web World!!",30);
      str.Replace("World", "Arena");

      Console.WriteLine(str);
   }
}

Output

Web Arena!!

Immutable string

Immutable string is a String in C#. A new memory is created every time. A String cannot be changed once it is created, unlike StringBuilde. It does not create a new object in the memory.

Set a string −

String str = “tim”;

The following is an example of a string in which we are comparing two string −

Example

 Live Demo

using System;

namespace StringApplication {

   class StringProg {

      static void Main(string[] args) {
         string str1 = "Steve";
         string str2 = "Ben";

         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}

Output

Steve and Ben are not equal strings.

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements