Compartilhar via


How to: Concatenate Multiple Strings (C# Programming Guide)

Concatenation is the process of appending one string to the end of another string. When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs. However, string variables can be concatenated only at run time. In this case, you should understand the performance implications of the various approaches.

Example

The following example shows how to split a long string literal into smaller strings in order to improve readability in the source code. These parts will be concatenated into a single string at compile time. There is no run time performance cost regardless of the number of strings involved.

static void Main()
{
    // Concatenation of literals is performed at compile time, not run time. 
    string text = "Historically, the world of data and the world of objects " +
    "have not been well integrated. Programmers work in C# or Visual Basic " +
    "and also in SQL or XQuery. On the one side are concepts such as classes, " +
    "objects, fields, inheritance, and .NET Framework APIs. On the other side " +
    "are tables, columns, rows, nodes, and separate languages for dealing with " +
    "them. Data types often require translation between the two worlds; there are " +
    "different standard functions. Because the object world has no notion of query, a " +
    "query can only be represented as a string without compile-time type checking or " +
    "IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " +
    "objects in memory is often tedious and error-prone.";

    Console.WriteLine(text);
}

To concatenate string variables, you can use the + or += operators, or the String.Concat, String.Format or StringBuilder.Append methods. The + operator is easy to use and makes for intuitive code. Even if you use several + operators in one statement, the string content is copied only once. But if you repeat this operation multiple times, for example in a loop, it might cause efficiency problems. For example, note the following code:

static void Main(string[] args)
{
    // To run this program, provide a command line string. 
    // In Visual Studio, see Project > Properties > Debug. 
    string userName = args[0];
    string date = DateTime.Today.ToShortDateString();

    // Use the + and += operators for one-time concatenations. 
    string str = "Hello " + userName + ". Today is " + date + ".";
    System.Console.WriteLine(str);

    str += " How are you today?";
    System.Console.WriteLine(str);

    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
}

// Example output:  
//  Hello Alexander. Today is 1/22/2008. 
//  Hello Alexander. Today is 1/22/2008. How are you today? 
//  Press any key to exit. 
//

Note

In string concatenation operations, the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.

If you are not concatenating large numbers of strings (for example, in a loop), the performance cost of this code is probably not significant. The same is true for the String.Concat and String.Format methods.

However, when performance is important, you should always use the StringBuilder class to concatenate strings. The following code uses the Append method of the StringBuilder class to concatenate strings without the chaining effect of the + operator.

class StringBuilderTest
{
    static void Main()
    {
        string text = null;

        // Use StringBuilder for concatenation in tight loops.
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < 100; i++)
        {
            sb.AppendLine(i.ToString());
        }
        System.Console.WriteLine(sb.ToString());

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
// Output: 
// 0 
// 1 
// 2 
// 3 
// 4 
// ... 
//

See Also

Reference

String

StringBuilder

Concepts

C# Programming Guide

Other Resources

Strings (C# Programming Guide)