Friday 11 May 2018

Difference Between string and StringBuilder in C#


    String is class and string is datatype, string is alias name of String, so there is no difference between string and String. String is immutable which cannot change in size and StringBuilder is mutable which can change in size. The following example shows the difference between string and StringBuilder.


using System;
using System.Text;

namespace CSHARP_String_StringBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            //string is Immutable, Immutable means unchangeable or fixed (size), so that if we try to add another string to the existing string variable, it creates new string instance and appends the string to the existing string.
            string abc = "veera";
            // creates a new string instance instead of changing the existing string
            abc += "swamy";
            Console.WriteLine(abc);
            //StringBuilder is Mutable, Mutable means changeable, so the size of the memory of exising instance increases while try to append new string to the StringBuilder.
            StringBuilder sb = new StringBuilder();
            sb.Append("Ramachandra");
            sb.Append("kumar");
            Console.WriteLine(sb);
            Console.ReadKey();
        }
    }
}

Output :-


 Both looks to be same but internally string creates new instances every time while trying to append another string value And StringBuilder remains the existing instance and increase the size of the existing instance while try to append new string.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.