Example 1 — Append, Insert, and ToString
Build a short message in a few steps, fix its front, and turn the buffer into a string.
using System;
using System.Text;
class Program {
static void Main() {
StringBuilder sb = new StringBuilder();
sb.Append("learn");
sb.Append(' ').Append("C#");
Console.WriteLine(sb.ToString());
sb.Insert(0, "Let's ");
sb.Append('!');
string message = sb.ToString();
Console.WriteLine(message);
Console.WriteLine(message.Length);
}
} How It Works
- An empty buffer.
new StringBuilder()starts with no text. It needsusing System.Text;, because that is the namespace the class lives in. - Grow it at the end.
Append("learn")adds a word, and the chainedAppend(' ').Append("C#")adds a space and another word to the very same builder. - Edit the front.
Insert(0, "Let's ")pushes the existing text to the right and puts the new words at position 0. No new string object is created for this step. - Finish with ToString.
ToString()copies the buffer into a realstring. The message has 15 characters: 6 forLet's, 8 forlearn C#, and 1 for the!.

