What is the Difference Between String and StringBuilder Classes in C#?

Learn: What is the difference between String and StringBuilder class in C#.Net, learn where and when these classes are used?
By IncludeHelp Last updated : April 06, 2023

Overview

String and StringBuilder both classes are used to manage strings in C#, still they have some difference, in this post we are going to learn what are the difference between them?

C# String Class

String class is immutable or read-only in nature. That means object of String class is read only and it cannot be modify the value of String object. It creates a new 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 initially assigned with value "India". But when we concatenate value to object, it actually creates new object in memory.

C# StringBuilder Class

StringBuilder class is mutable in nature. That means the object of StringBuilder class can be modified, we can perforce string manipulation related operations like insert, remove, append etc with the object. It does not create a new object; changes done with the StringBuilder class's object always modify the same memory area.

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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.