c#

What is the difference between string and stringbuilder C#?

A:

String Builder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but String Builder is the mutable string type. It will not create a new modified instance of the current string object but do the modifications in the existing string object. The complete functionality of StringBuilder is provided by StringBuilder class which is present in System.Text namespace.

Ex:

using System; 

using System.Text; 

using System.Collections; 

class GFG { 

    public static void concat1(String s1) 

    { 

        String st = “ASP.NET”; 

        s1 = String.Concat(s1, st); 

    } 

    public static void concat2(StringBuilder s2) 

    { 

        s2.Append(“ASP.NET”); 

    } 

    // Main Method 

    public static void Main(String[] args) 

    { 

        String s1 = “Tutorial”; 

        concat1(s1); // s1 is not changed 

        Console.WriteLine(“Using String Class: ” + s1); 

        StringBuilder s2 = new StringBuilder(“Tutorial”); 

        concat2(s2); // s2 is changed 

        Console.WriteLine(“Using StringBuilder Class: ” + s2); 

    } 

}

Output:

Using String Class: Tutorial

Using StringBuilder Class: ASP.NET Tutorial

Leave a comment

Your email address will not be published. Required fields are marked *