How to: Join Multiple Strings (C# Programming Guide)
There are two ways to join multiple strings: using the + operator that the String class overloads, and using the StringBuilder class. The + operator is easy to use and makes for intuitive code, but it works in series; a new string is created for each use of the operator, so chaining multiple operators together is inefficient. For example:
string two = "two";
string str = "one " + two + " three";
System.Console.WriteLine(str);
Although four strings appear in the code, the three strings being joined and the final string containing all three, five strings are created in total because the first two strings are joined first, creating a string containing "one two." The third is appended separately, forming the final string stored in str
.
Alternatively, the StringBuilder class can be used to add each string to an object that then creates the final string in one step. This strategy is demonstrated in the following example.
Example
The following code uses the Append method of the StringBuilder class to join three strings without the chaining effect of the + operator.
class StringBuilderTest
{
static void Main()
{
string two = "two";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("one ");
sb.Append(two);
sb.Append(" three");
System.Console.WriteLine(sb.ToString());
string str = sb.ToString();
System.Console.WriteLine(str);
}
}