C-SHARP - 4.8 StringBuilder
This video introduces the StringBuilder class. A reminder first: a string in C# is an object of the String class and it is immutable. Every method we call on it returns a brand-new string in memory, which means each modification allocates fresh memory. When we perform many modifications in a loop, the overhead becomes significant.
To work around this, the .NET framework offers StringBuilder, which holds an internal mutable buffer. Operations such as concatenation, insertion and replacement happen inside the same object, avoiding repeated allocations. StringBuilder is optimised for editing but, unlike String, it does not expose search methods such as IndexOf or LastIndexOf.
using System.Text;
var builder = new StringBuilder();
builder.Append('*', 10);
builder.AppendLine();
builder.Append("Welcome");
builder.Replace('*', '-');
builder.Remove(0, 5);
builder.Insert(0, "+++");
Console.WriteLine(builder);
Most useful methods
Append/AppendLine: add content at the end of the buffer.Insert(index, value): insert content at a specific position.Remove(index, length): delete a portion of the buffer.Replace(oldValue, newValue): substitute a character or substring.Clear(): empty the entire builder.
You will use StringBuilder whenever you need to concatenate many fragments in a loop or build a long, dynamic output. For one-off transformations the String class is fine; for heavy editing the builder pays off in performance. The next video walks through these methods step by step on Visual Studio.