Read the syntax
StringBuilder accumulates mutable text efficiently across a loop. Convert the finished buffer to a string when passing it to code that expects immutable text. Use a .NET 8+ console project; replace Program.cs with this C# example.
One mutable buffer receives each fragment. The condition adds separators between items without a trailing comma.
Syntax
builder.Append(value); builder.ToString()Examples
StringBuilder Text Accumulation
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
using System.Text;
var builder = new StringBuilder();
for (int i = 1; i <= 3; i++)
{
if (i > 1) builder.Append(", ");
builder.Append("item-").Append(i);
}
Console.WriteLine(builder.ToString());- Expected output: item-1, item-2, item-3
- One mutable buffer receives each fragment. The condition adds separators between items without a trailing comma.
- Use interpolation for short fixed messages.
Best practices
- Use interpolation for short fixed messages.
- Keep mutable builders local rather than sharing them between concurrent callers.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference