This is Part 1 in the series of Joining stings

The third way to join strings is to use a class called the StringBuilder.

The StringBuilder is a mutable string of characters. (Remember that a string, by design, is immutable).

You typically interact with a StringBuilder by creating one, and then adding strings to it using the Append method.

// Create a new, empty StringBuilder 
var simpsons = new StringBuilder();
simpsons.Append("Marge");
simpsons.Append("Homer");
simpsons.Append("Bart");
simpsons.Append("Lisa");

// Write string to console
Console.WriteLine(simpsons);

You can also create a StringBuilder with a constructor that takes a string.

// Create a StringBuilder that is initialized
var griffins = new StringBuilder("Peter");
griffins.Append("Lois");
griffins.Append("Meg");
griffins.Append("Chris");
griffins.Append("Stewie");

// Write string to console
Console.WriteLine(griffins);

Should you want to manipulate the strings prior to appending them, there is a method that allows you to append strings using the String.Format syntax

var holidays = new StringBuilder();
holidays.AppendFormat("New Year's Day {0:d MMM yyyy}", new DateTime(2020, 1, 1));
Console.WriteLine(holidays);

With string interpolation, you can do this directly:

holidays.Append($"Christmas { new DateTime(2020, 12, 25):d MMM yyyy}");

If you look at the output, it looks something like this:

You might ask - what if you want to introduce newlines between each string?

There are two ways.

The simplest is instead of using the Append method, you use the AppendLine method.

var newHolidays = new StringBuilder();
newHolidays.AppendLine($"Labour Day { new DateTime(2020, 5, 1):d MMM yyyy}");
newHolidays.AppendLine($"Boxing Day { new DateTime(2020, 12, 26):d MMM yyyy}");
Console.WriteLine(newHolidays);

Alternatively you can use either AppendFormat or string interpolation to introduce the newlines.

Interestingly, when you use string interpolation, the compiler rewrites the code to use AppendFormat.

The former code, when passed to SharpLab, generates the following:

Given that a StingBuilder is mutable, this allows a number of operations that are generally not possible with immutable strings.

You can modify the contents of a StringBuilder.

newHolidays[6] = '-';

This will change the output from:

Labour Day 1 May 2020

to:

Labour Day-1 May 2020

You can also insert text into any position in the StringBuilder.

In the example below we are inserting text at the very beginning.

newHolidays.Insert(0, $"Valentines' Day {new DateTime(2020, 2, 14):d MMM yyyy}{Environment.NewLine}");

Regardless of the number of strings you are joining, the StringBuilder internally adjusts its capacity to accommodate the changes.

This means that if you are manipulating a large number of strings, you can get a lot of performance benefits from using a StringBuilder.

The code is in my Github.

Happy hacking!