Dot Net Perls

String Concat Samples - C#

by Sam Allen

Problem. You need to know ways to concat strings in C#. Samples can refresh your memory. Solution. This document contains lots of information, samples, and benchmarks.

Question: how can I combine two strings in C#?

By using the plus operator or the string.Concat method. Internally, C# converts the plus operator into string.Concat, so only the syntax is different.

using System;

class Program
{
    static void Main()
    {
        // 1.
        // New string called s1.
        string s1 = "string2";

        // 2.
        // Add another string to the start.
        string s2 = "string1" + s1;

        // 3.
        // Write to console.
        Console.WriteLine(s2);
        // "string1string2"

        Console.ReadLine();
    }
}

Performance of combining two strings with plus or string.Concat is excellent and using other methods for just two strings is slower. Here's the equivalent code with string.Concat.

using System;

class Program
{
    static void Main()
    {
        // 1.
        string s1 = "string2";

        // 2.
        string s2 = string.Concat("string1", s1);

        // 3.
        Console.WriteLine(s2);
        // "string1string2"

        Console.ReadLine();
    }
}

Question: how can I concatenate three strings in C#?

Use the same string.Concat or plus operator as for two strings. My testing shows this has good performance and is simpler than other methods such as string.Format.

using System;

class Program
{
    static void Main()
    {
        // 1.
        string s1 = "string1";

        // 2.
        string s2 = "string2";

        // 3.
        // Combine three strings.
        string s3 = s1 + s2 + "string3";

        // 4.
        // Write the result to the screen.
        Console.WriteLine(s3);
        // "string1string2string3"

        Console.ReadLine();
    }
}

string.Concat with three arguments works equally well here too. Note that you can use the + in any order, just like method arguments.

Question: how can I add one string to the start of another?

This is called prepending and you can use the same + or string.Concat methods. Performance here is good and which method to use depends on what you find clearer.

You can append strings by using + or string.Concat as well. However, for many appends in a row, consider StringBuilder.

Question: how can I concatenate four strings in C#?

First, you can use the same syntax above. Here we start seeing performance changes. For four strings, it is fastest to add them all in a single statement, with string.Concat or +. You will find the benchmarks interesting.

string.Format also becomes more usable appending many strings here. However, it suffers from much worse performance.

Additionally, we start considering StringBuilder when multiple strings are encountered. It also has much worse performance at this level though.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string s1 = "string1";
        // A.
        // Concat 4 strings, one at a time.
        {
            string s2 = "string1" + s1;
            s2 += "string2";
            s2 += s1;
            Console.WriteLine(s2);
        }
        // B.
        // Concat 4 strings, all at once.
        {
            string s2 = string.Concat("string1",
                s1,
                "string2",
                s1);
            Console.WriteLine(s2);
        }
        // C.
        // Concat 4 strings using a format string.
        {
            string s2 = string.Format("string1{0}string2{0}",
                s1);
            Console.WriteLine(s2);
        }
        // D.
        // Concat 4 strings, three at a time then one.
        {
            string s2 = "string1" + s1 + "string2";
            s2 += s1;
            Console.WriteLine(s2);
        }
        // E.
        // Concat 4 strings, one at a time with StringBuilder.
        {
            string s2 = new StringBuilder("string1").Append(
                s1).Append("string2").Append(s1).ToString();
            Console.WriteLine(s2);
        }
        Console.ReadLine();
    }
}

When executed, The above console program will show the following output. All five methods resulted in the same exact line output.

string1string1string2string1
string1string1string2string1
string1string1string2string1
string1string1string2string1
string1string1string2string1

Question: how fast are the string concats?

What I display here is the benchmarks for 4 strings combined into one. For fewer than 4 strings, using string.Concat or + is very fast and also clearest to read. But there are more options for 4 strings.

Six methods compared. I compared the methods A - E above. I had to write several programs to benchmark them, so all the code is not available.

Note on benchmark. To prevent the compiler from solving the program before it is run, I built up one of the strings at runtime. This provides accurate results.

What it shows. At four strings of short lengths, using string.Concat or + on all the strings in one statement is best. The slowest method is string.Format.

Question: how can I concatenate five strings?

You can use the same methods as shown above. Here the performance changes radically and we have to look into the IL to see why.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string s1 = "string1";
        // A.
        // Concat 5 strings in two statements.
        {
            string s2 =
                s1 +
                "string1" +
                s1 +
                "string2";
            s2 += s1;
            Console.WriteLine(s2);
        }
        // B.
        // Concat 5 strings in one statement.
        {
            string s2 =
                s1 +
                "string1" +
                s1 +
                "string2" +
                s1;
            Console.WriteLine(s2);
        }
        // C.
        // Concat 5 strings in StringBuilder.
        {
            string s2 = new StringBuilder(s1).Append(
                "string1").Append(s1).Append(
                "string2").Append(s1).ToString();
            Console.WriteLine(s2);
        }
        Console.ReadLine();
    }
}

What it does. A, B and C above combine five strings in different ways. The first method uses two statements to combine the strings. B uses a single statement. C uses StringBuilder. Here's the output.

string1string1string1string2string1
string1string1string1string2string1
string1string1string1string2string1

What's going on. I was surprised to find that A is the fastest here. Suddenly, using string.Concat or + on all strings at once in B is not the best. Here's some more analysis.

Question: why is concatenating 5 strings different?

In the .NET framework, there are string.Concat overloaded methods that accept between two and four parameters. Finally, there is an override that accepts an array. When you concat 5 strings, the array overload method is used. [C# - Overload Methods - dotnetperls.com]

Looking into Reflector, we see a list of many Concat methods. However, there isn't one with five arguments specifically. When 5 arguments are needed, the params version is used.

Looking even deeper, I saw that the internals use ConcatArray, which seems to have a much different implementation. Unfortunately, this overload doesn't perform as well as the ones with fewer parameters.

Question: what's the fastest way to concatenate 5 strings?

My research shows: first concat 4 strings, then concat that with more strings. Instead of combining all strings at once, it is faster to combine four at a time. This won't result in needing the ConcatArray internal method.

Is this useful? It depends. However, I feel understanding exactly how strings are concatenated is extremely useful. The performance difference between 4 concats at once and 5 concats at once is relevant.

Information: what MSDN tells us

It provides information on the string.Concat overloads. Look at the links to the methods that accept arrays and those that don't. [String.Concat Method (System) - dotnetperls.com]

ItemMicrosoft's description
System.Text.StringBuilder...Using the StringBuilder class can boost performance when concatenating many strings together in a loop.
(It specifies loop.)
String// The + operator concatenates strings: string a = "good " + "morning";

Information: Dot Net Perls' string concat guidelines

When you need to combine fewer than 5 strings, always use one statement. This statement should use string.Concat directly or the + operator.

However, When you need to concat 5 or more strings, use multiple statements of 4 strings at once. This is appropriate for when you have a known number of strings.

Further, if you have a loop or could have many more than 5 strings, use StringBuilder. This may perform worse sometimes, but it will prevent edge cases of huge numbers of strings from causing problems.

Question: what did we accomplish here?

We looked into some of the internals of string combining. We saw samples of combining 2, 3, 4 and 5 strings at once. My benchmarks gave you some data points about what statements are more efficient.

In every program, you will likely append or concat strings. Further research on this site or elsewhere can increase your knowledge.

Tip: read my other articles

I have lots of material on StringBuilder, string.Intern, string.Empty, counting characters in strings, splitting strings, sorting strings, and manipulating words in strings.

Finally, regular expressions can solve many of the more difficult string problems. Look into System.Text.RegularExpressions and Regex in C#.

Dot Net Perls
About
Sitemap
Strings
Split String Examples
IndexOf String Examples
Replace String Examples
Remove HTML Tags From String
Remove Duplicate Words From...
New
StartsWith String Examples
GZIP Accept-Encoding Request
© 2008 Sam Allen. All rights reserved.