Home » .Net

Difference between String and StringBuilder class in C#

Learn: What is the difference between String and StringBuilder class in C#.Net, learn where and when these classes are used?

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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.