StringBuilder Class
The StringBuilder
class represents a mutable string of characters. It provides an efficient way to modify strings without creating new string instances.
Namespace: System.Text
Assembly: System.Runtime.dll
Constructors
StringBuilder()
StringBuilder(string)
StringBuilder(int capacity)
StringBuilder(string, int capacity)
Initializes a new instance of the StringBuilder
class.
var sb = new StringBuilder();
Initializes with the specified string.
var sb = new StringBuilder("Hello");
Initializes with a specified capacity.
var sb = new StringBuilder(capacity: 256);
Initializes with a string and capacity.
var sb = new StringBuilder("Hello", capacity: 128);
Key Methods
- Append(string) – Adds the specified string to the end of the current instance.
- AppendLine() – Appends the default line terminator.
- Insert(int, string) – Inserts a string at the specified index.
- Remove(int, int) – Deletes a range of characters.
- Replace(string, string) – Replaces all occurrences of a specified string.
- ToString() – Returns a string representation of the current instance.
var sb = new StringBuilder();
// Build a multi‑line string
sb.AppendLine("First line")
.AppendLine("Second line")
.Append("End");
string result = sb.ToString();
Important Properties
- Capacity – Gets or sets the number of characters that the current
StringBuilder
can hold without resizing. - Length – Gets or sets the number of characters currently in the
StringBuilder
. - MaxCapacity – Gets the maximum capacity of the current instance.
- Chars[int] – Gets or sets the character at the specified index.
var sb = new StringBuilder("ABC");
sb[1] = 'X'; // becomes "AXC"
sb.Length = 2; // truncates to "AX"
Practical Example – Building CSV
using System;
using System.Text;
class Program {
static void Main() {
var sb = new StringBuilder();
string[] headers = { "Id", "Name", "Email" };
sb.AppendLine(string.Join(",", headers));
for (int i = 1; i <= 5; i++) {
sb.AppendLine(${i},{"User"+i},{"user"+i+"@example.com"}});
}
Console.WriteLine(sb.ToString());
}
}