How to: Join Multiple Strings
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

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";

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.


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(" three");

        string str = sb.ToString();

See Also

© 2015 Microsoft