The string is an immutable type in C#, which means it can’t be changed once it’s been created. StringBuilder, on the other hand, is mutable, which means that if an operation is performed on the string object, it won’t construct a new instance in memory every time, unlike string.

In C#, string, and StringBuilder are both used to store and manipulate sequences of characters. However, there are some key differences between these two types that you should consider when choosing which one to use in your code.
- A string is immutable, which means that once you create a string, you cannot modify it. This can make it more efficient when you only need to read or compare strings, but it can be less efficient when you need to build or modify a string repeatedly.
- On the other hand, StringBuilder is mutable, which means that you can change it after it is created. This makes it ideal for situations where you need to build or modify a string repeatedly, as it can be more efficient than using string for this purpose. However, keep in mind that StringBuilder may use more memory than strings in some cases.
In summary, if you only need to read or compare strings, you should use a string. If you need to build or modify a string repeatedly, you should use a StringBuilder.
Table of Contents
- 1 Difference between string and StringBuilder in C#
- 2 String in C#
- 3 StringBuilder in C#
- 3.1 StringBuilder memory allocation
- 3.2 Declaration and Initialization of StringBuilder in C#
- 3.3 Setting the capacity and length of the StringBuilder
- 3.4 C# StringBuilder Methods
- 3.5 C# StringBuilder Append/AppendLine Method
- 3.6 StringBuilder AppendFormat Method
- 3.7 C# StringBuilder Insert Method
- 3.8 StringBuilder Remove Method
- 3.9 StringBuilder Replace Method
- 3.10 Use of Indexer in StringBuilderStringBuilder as Indexer
- 3.11 Convert StringBuilder to String
- 4 Summary:
- 5 FAQs
Difference between string and StringBuilder in C#
The differences between the string and StringBuilder are listed below.
C# String | C# StringBuilder |
---|---|
1. The string class is available in System Namespace. | The StringBuilder class is available in System.Text Namespace |
2. A string instance is immutable (unchangeable). String objects once created cannot be changed. | A StringBuilder class is mutable (changeable), which means if we create a string builder instance then we can perform any operation on it. |
3. If we perform any operation on a String instance, it will create a new instance in the heap memory instead of modifying the existing string value. Example: string stringValue = “Hello “; // creating a new string instance instead of modifying the old one. stringValue += “World”; | If we perform any operation on a StringBuilder instance, it will update the existing instance value rather than creating a new one in the memory. Example: StringBuilder sb = new StringBuilder(); sb.Append(“Hello “); sb.Append(“World”); string stringValue = sb.ToString(); |
4. Because String is immutable, it can be used across multiple threads without causing synchronization issues. Thread safety is ensured. | The StringBuilder in C# is not thread-safe since it lacks synchronization. |
5. Performance degrades when heavy string manipulations or concatenation are involved. | StringBuilder is mutable, So it provides better performance as compared to the String object because the new changes are made to an existing instance instead of creating the new one in the memory. |
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.
- The string is immutable (unchangeable), and 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.

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 garbage collection.
String concatenation can be done in two ways, either by using the + = 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.
The following is the pictorial representation of memory allocation for the unique strings.

The following is the Sample example code :
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();
}
}

In the above example, the 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.
The 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.
Method Name | Description |
---|---|
Append | Appends the given information to the end of the current StringBuilder. |
AppendFormat | Replaces a format specifier passed in a string with formatted text. |
Insert | Inserts a string or object into the specified index of the current StringBuilder. |
Remove | It removes/deletes a specified number of characters from the current StringBuilder. |
Replace | Replaces a specified character at a specified index of the current StringBuilder. |
StringBuilder memory allocation
Pictorial representation of memory allocation for the unique strings.

The following is the sample example code of using StringBuilder in C#.
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 in C#
In C# the declaration and initialization of the StringBuilder are the same as the 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);
C# StringBuilder Methods
The following are some commonly used methods of the StringBuilder
class:
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. The AppendLine
method appends the string with a new line at the end of the string.
Example:
The following are the sample code 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
C# 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.
The following are the sample code 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 StringBuilder
In C# we can use the 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 two methods.
-
- StringBuilder.ToString()
- Convert.ToString(StringBuilder)
Program to convert a 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
References: MSDN- StringBuilder in C#
Summary:
In this article, we talked about the difference between String and StringBuilder with multiple examples.
To sum up, when working with sequences of characters in C#, it is important to consider whether you need to modify the string or not. If you only need to read or compare strings, it is more efficient to use a string, as it is an immutable object. However, if you need to build or modify a string repeatedly, you should use a StringBuilder, as it is a mutable object that is more efficient for this purpose. It is important to choose the right type for your needs to ensure that your code is as efficient as possible. Keep in mind that StringBuilder may use more memory than strings in some cases.
I hope this post was helpful and enjoyable. If you have any questions or suggestions, please feel free to leave a comment.
FAQs
The following are some common questions and answers about strings and StringBuilder in C#:
Q: What is a string in C#?
A: A string in C# is an immutable object that represents a sequence of Unicode characters. This means that once a string is created, it cannot be modified.
Q: What is a StringBuilder in C#?
A: A StringBuilder in C# is a mutable object that represents a modifiable string of characters. It is designed for situations where we need to build or modify a string repeatedly.
Q: When should I use a string and when should I use a StringBuilder in C#?
A: You should use a string
when you need an immutable object to hold a sequence of characters. You should use a StringBuilder
when you need to build or modify a string repeatedly, as it can be more efficient than using strings for this purpose.
Q: Can you use a StringBuilder to hold a large amount of text?
A: Yes, you can use a StringBuilder
to hold a large amount of text. However, keep in mind that StringBuilders are mutable objects, so they may use more memory than strings in some cases.
Q: Can we convert a StringBuilder to a string?
A: Yes, we can convert a StringBuilder to a string using the ToString
method.
For example:string str = sb.ToString();
.
Recommended Articles:
- Top 10 Difference between interface and abstract class In C#
- C# List Class |Top 12 Amazing Generic List Methods
- Exception Handling in C#| Use of try, catch and finally block
- C# Enum
- C# extension methods with examples
- Properties In C# with examples
- IEnumerable Interface in C# with examples
- URL vs URI: The Ultimate Guide to Understanding the difference between URL and URI
- Constructors in C# with Examples
- C# Dictionary
- Readonly vs const in C#
- Difference between SortedList and SortedDictionary in C#
- Jump Statements in C# (Break, Continue, Goto, Return, and Throw)
- Is vs As operator in C#: Understanding the differences between is and as operator in C#
- Singleton Design Pattern in C#: A Beginner’s Guide with Examples
- SOLID Design Principles in C#: A Complete Example
- Understanding the SOLID Principle: Single Responsibility Principle in C# - June 7, 2023
- Difference between var and dynamic in C# - May 26, 2023
- Understanding the Chain of Responsibility Design Pattern in C# - May 11, 2023
Sir,
If suppose I Concat string 10 times.
10 objects will be created in memory.
The 10th object will be used and the remaining ones will be in the memory.
What will GC do of 9 objects??
Will it remove all the 9 objects?
If all 9 objects are removed by GC then why use String Builder?
Hello, Jaydeep. There are no precise times when the garbage collector is triggered, thus if you produce ten string objects, you never know when the remaining nine string objects will be disposed of from memory by the garbage collector.
The garbage collector searches for objects that are no longer in use and frees up memory, but you never know when it will be invoked. Any objects still in use will survive and promote to the next generation.