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

Immutable String: Immutable string can’t be alter, once we have assign a value to immutable object state can’t be changed. We can use System.String to use immutable string.

   String str = “Technology Crowds”;  //*  Immutable String Example
   string str = “Technology Crowds” + “Technology”;
Mutable vs Immutable

Mutable String: We can assign multiple values to mutable string and object state can be altered.
Best example of Mutable is stringbuilder object can be used. We can multiple concatenation to mutable string. Mutable have very good flexibility to change object state, mutable string can generate long string.
We can use given below namespace to use mutable string in c#

    using System.Text;   //*  namespace used to import string builder

  StringBuilder strLong = null;   //*  [Mutable String] example

I have clarified above best practice of mutable and immutable string in c#.

No comments:

Post a Comment