C# Language String Concatenate Concatenate strings using System.Text.StringBuilder

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Concatenating strings using a StringBuilder can offer performance advantages over simple string concatenation using +. This is due to the way memory is allocated. Strings are reallocated with each concatenation, StringBuilders allocate memory in blocks only reallocating when the current block is exhausted. This can make a huge difference when doing a lot of small concatenations.

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    sb.Append(i);
    sb.Append(" ");
}
Console.WriteLine(sb.ToString()); // "1 2 3 4 5 "

Calls to Append() can be daisy chained, because it returns a reference to the StringBuilder:

StringBuilder sb = new StringBuilder();
sb.Append("some string ")
  .Append("another string");


Got any C# Language Question?