Difference between String and StringBuilder class in C#

Realize: What are the contrast among String and StringBuilder class in C#.Net, realize where and when these classes are utilized?

String and StringBuilder the two classes are utilized to oversee strings in C#, still, they have some distinction, in this post we will realize what is the contrast between them?

C# String Class

String class is permanent or read-just in nature. That implies an object of String class is perused just and it can’t alter the benefit of the String object. It makes another object of string type in memory.

String Class Example in C#:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String s = "India ";

            //Here it creates new object instead of modifing old object
            s += "is the best ";
            s += "country";

            Console.WriteLine(s);
        }
    }
}

Output:

India is the best country

In this program object s at first appointed with esteem “India“. However, when we link an incentive to protest, it really makes a new item in memory.

C# StringBuilder Class:

StringBuilder class is variable in nature. That implies the object of StringBuilder class can be altered, we can perforce string control related activities like a supplement, expel, affix and so forth with the article. It doesn’t make another article; changes finished with the StringBuilder class’ item consistently alter a similar memory territory.

StringBuilder Class Example in c#:

using System;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder s = new StringBuilder("India ");

            //Here it creates new object instead of modifing old object
            s.Append("is the best ");
            s.Remove(0,5);
            s.Insert(0, "Bharat");
            
            Console.WriteLine(s);

            s.Replace("Bharat", "Hindustan");
            Console.WriteLine(s);
        }
    }
}

Output:

Bharat is the best
Hindustan is the best

Leave a Comment

error: Alert: Content is protected!!