Difference Between String and StringBuilder in C#

String in C#

In C#, String is a keyword that is used to hold the text value. It is an object of System.String type.

String is immutable (unchangeable), the value once assigned to a String object cannot be modified after its creation.

If we try to change the value of the String object, it will create a new instance in a different memory location with the modified value.
In C#, a string is a series of characters that is used to represent text.

String memory allocation

Following is the pictorial representation of memory allocation for the string.

String memory allocation in heap
String memory allocation in the heap memory

Example of string concatenation

using System;
class Program
{
    static void Main(string[] args)
    {
        string str = "Hello ";

              str += "Shekh";

        // Here Concatenation (+=) actually creating a new
        // string object and releasing the
        // reference to the original object.

        Console.WriteLine(str);
        Console.ReadLine();
    }
}
// Output: Hello Shekh

The += operator creates a new string object that contains the combined contents. The previous objects get released for the garbage collection.

String concatenation can be done in two ways, either by using + = operator or by using the String.Concat method.

string str = "Hello ";

str = String.Concat(str, "Shekh");

String interning in C#

In C#, sometimes we write a program with multiple instances of the same string.
The CLR (Common Language Runtime) stores single references to all unique strings in a special table known as Intern Pool.

    • At compilation time all the unique strings are allocated in the heap memory.
    • Only the reference is returned from the “Intern Pool” to the new string variables having the same value.

Pictorial representation of memory allocation for the unique strings.

String interning in C#
String interning in C#

Example:

using System;
class Program
{
    static void Main(string[] args)
    {
        string x = "SameString";

        string y = "SameString";

        string z = "DifferentString";

        Console.WriteLine("x == y {0}", Object.ReferenceEquals(x, y));
        Console.WriteLine("y == z {0}", Object.ReferenceEquals(y, z));

        Console.ReadLine();
    }
}


The output of the above C# program.

In the above example, x and y variables have the same reference.

  • In C# Strings are immutable.
  • Every time we concatenate a string a new object is created in the heap memory.
  • In C# the previous objects which are no longer used are garbage collected.
  • Modifying the same string multiple times will hinder the performance
  • In C# use StringBuilder if the string is modifying frequently.

StringBuilder in C#

In C# we use String and StringBuilder to hold text. The only difference is the String is immutable and StringBuilder is mutable.

StringBuilder is a dynamic object which belongs to the System.Text namespace.  It doesn’t create a new object in the heap memory every time we concatenate a new string.

    • In C# the StringBuilder is the better option for concatenating multiple strings together in a loop.
    • The string is efficient if we are only concatenating two or three strings.

StringBuilder memory allocation

Pictorial representation of memory allocation for the unique strings.

StringBuilder memory allocation
Memory allocation for the StringBuilder in the Heap

Example of StringBuilder.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
                      sb.Append("Hello ");
                      sb.Append("World");

        Console.WriteLine(sb);
        Console.ReadLine();
    }
}
// Output: Hello World


Declaration and Initialization of StringBuilder class in C#

In C# the declaration and initialization of the StringBuilder are the same as class.

StringBuilder sb = new StringBuilder();
//or
StringBuilder sb = new StringBuilder(“Hello World”);

In the above code, ‘sb’ is the object of the StringBuilder class.
In C# we can create a new instance of the StringBuilder class by passing the value in the constructor

Setting the capacity and length of the StringBuilder

In C# StringBuilder allows us to set the maximum number of characters it can hold. After the maximum capacity is reached, a new space for the StringBuilder is allocated in the heap.

StringBuilder sb = new StringBuilder();
sb.Capacity = 10;
//or
StringBuilder sb = new StringBuilder(10);

//or
StringBuilder sb = new StringBuilder(“Hello World”, 10);

StringBuilder Methods

Method Name Description
StringBuilder.Append Appends the given information to the end of the current StringBuilder.
StringBuilder.AppendFormat Replaces a format specifier passed in a string with formatted text.
StringBuilder.InsertInserts a string or object into the specified index of the current StringBuilder.
StringBuilder.RemoveIt removes/deletes a specified number of characters from the current StringBuilder.
StringBuilder.ReplaceReplaces a specified character at a specified index of the current StringBuilder.

C# StringBuilder Append/AppendLine Method

In C# we use the Append method to add a new text or string at the end of the string represented by the StringBuilder.
AppendLine method appends the string with a newline at the end of the string.

Example:

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("Hello ");

        sb.AppendLine("World");

        //Text append with a new line
        sb.AppendLine("This is a new Line");

        Console.WriteLine(sb);
        Console.ReadLine();
    }
}

/* Output:
Hello World
This is a new Line
*/

StringBuilder AppendFormat Method

In C# we can use the AppendFormat method to format the input string into a specified format. which can append at the end of the string represented by the StringBuilder.

In the below example we are using the AppendFormat method to place an integer value formatted as a currency ($) value .

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Total amount: ");

        int amount = 250;    

        sb.AppendFormat($"{amount:C} ");

        Console.WriteLine(sb);

        Console.ReadLine();
    }
}
// The example displays the following output:
// Total amount:  $250.00

StringBuilder Insert Method

In C# the Insert method adds a string or an object to a specified position in the StringBuilder object.
Here we are inserting a word into the sixth position of a StringBuilder object.

Example:

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh");
        sb.Insert(6," Mr. ");
        Console.WriteLine(sb);
        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello  Mr. Shekh

StringBuilder Remove Method

In C# the Remove method of StringBuilder removes the string at the specified index with a specified length.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh");
        sb.Remove(5,6);
        Console.WriteLine(sb);
        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello

StringBuilder Replace Method

In C# the Replace method  of the StringBuilder replaces all occurrences of a specified string within the StringBuilder object by a specified replacement string.

Example:

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh ?");

        sb.Replace("?","!");

        Console.WriteLine(sb);

        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello Shekh !

Use of Indexer in StringBuilderStringBuilder as Indexer

In C# we can use indexer with StringBuilder to get or set characters at the specified index.
In the below example we are getting all the characters from the StringBuilder using for loop.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh");

        for(int index=0; index <sb.Length; index ++)
        {
            Console.Write(sb[index]);
        }

        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello Shekh

Convert StringBuilder to String

In C# we can convert a StringBuilder object to a string by using the below methods.

  • StringBuilder.ToString()
  • Convert.Tostring(StringBuilder)

Program to convert StringBuilder object to a string.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("Hello ");

        sb.Append("Shekh");

        //Convert StringBuilder to string
        Console.WriteLine(Convert.ToString(sb));
        //or
       // Console.WriteLine(sb.ToString());
        
        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello Shekh

Please read my next post about Types of Constructor in C#.

Thanks for visiting!

Leave a Reply

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

fifteen − 13 =