C# string.Concat Examples

Use string.Concat and the plus operator on strings. Append strings and measure performance.

dot net perls

String.Concat. With concat, strings are merged (combined). It is possible to concatenate 2 or more strings with several syntax forms.String Interpolation

Plus. We use the plus operator and the string.Concat method. The plus compiles into string.Concat. Another option is string.Join.
Tip: The main reason to use "+" instead of string.Concat is readability. Both expressions will compile into the same code.

An example. We concatenate 2 strings with plus. We then use the string.Concat method. The C# compiler converts the plus operator into string.Concat.
However: We concat a string literal ("string1") with a string variable (s1). The reference is stored in the s2 local.
String Literal
C# program that concatenates strings using System; class Program { static void Main() { // ... Create a new string reference. // It points to the literal. string s1 = "string2"; // ... Add another string to the start. string s2 = "string1" + s1; Console.WriteLine(s2); } } Output string1string2

Two strings. This example shows combining 2 strings with string.Concat. It is the same as using plus. Usually, calling string.Concat directly results in less clear code.
C# program that uses string.Concat method using System; class Program { static void Main() { string s1 = "string2"; string s2 = string.Concat("string1", s1); Console.WriteLine(s2); } } Output string1string2

Three strings. Here we use the same string.Concat or plus operator. You can use the + in any order, just like method arguments—which essentially is what the operands become.
Info: Adding to the start is called prepending. You can append strings by using + or string.Concat.
C# program that concats 3 strings using System; class Program { static void Main() { string s1 = "string1"; string s2 = "string2"; // Combine 3 strings. string s3 = s1 + s2 + "string3"; // Write the result to the screen. Console.WriteLine(s3); } } Output string1string2string3

List. We create a List instance and add 3 string literals to it. We can pass the List variable reference to the string.Concat method. It will concatenate all the strings with no separator.List
Note: The string.Concat method here is equivalent to the string.Join method invocation with an empty separator.
C# program that concats string list using System; using System.Collections.Generic; class Program { static void Main() { // Create list of 3 strings. var list = new List<string>(); list.Add("cat"); list.Add("dog"); list.Add("perls"); // Concat the list. string concat = string.Concat(list); Console.WriteLine(concat); // Join the list. string join = string.Join("", list); Console.WriteLine(join); } } Output catdogperls catdogperls

Benchmark, Concat. Sometimes we can use Concat (or the plus operator) or string.Format. Should we prefer Concat or Format when we have the choice?
Version 1: This version of the code uses Concat to combine 3 strings together into 1 string.
Version 2: Here we use string.Format, and a format string with 3 substitution markers, to combine the strings.
Result: The plus operator (which is the Concat method) is faster. We should avoid Format unless more advanced features are needed.
C# program that benchmarks Concat, Format using System; using System.Diagnostics; class Program { const int _max = 1000000; static void Main() { string value1 = "bird"; string value2 = "frog"; string value3 = "dog"; var s1 = Stopwatch.StartNew(); // Version 1: use string.Concat. for (int i = 0; i < _max; i++) { string result = value1 + value2 + value3; if (result == null) { return; } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use string.Format. for (int i = 0; i < _max; i++) { string result = string.Format("{0}{1}{2}", value1, value2, value3); if (result == null) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 34.33 ns + 124.46 ns string.Format

Performance, overloads. In the .NET Framework, there are Concat methods that accept between 2 and 4 parameters. And there is one that accepts an array.
Info: Looking into IL Disassembler, we see a list of many Concat methods. When 5 arguments are needed, the params version is used.
IL Disassembler
Thus: It may be faster to perform concatenations of at most 4 strings at a time. But usually using StringBuilder is a better choice.

Notes, internals. The internals use ConcatArray, which seems to have a different implementation. This overload doesn't perform as well as the ones with fewer parameters.Params

StringBuilder. If you have a loop or could have many more than 5 strings, use StringBuilder. This may perform worse, but it will prevent edge cases from causing problems.
Also: Microsoft provides information on the string.Concat overloads. Some accept arrays, and some do not.
String.Concat Method: Microsoft Docs

Notes, implementation. Should we use string.Concat or string.Join? The implementations in .NET 4.0 are the same except string.Join repeatedly appends the separator.
Note: Appending an empty string is fast, but not doing so is even faster, so the string.Concat method would be superior here.
Tip: The string.Concat method in the .NET Framework 4.0 has an overload that receives an IEnumerable collection of type string.

A summary. Strings are frequently combined (concatenated). The benchmarks here give some data data points about what statements are most efficient.

In many programs, you will append or concat strings. The string.Format method is an alternative. String interpolation can also be used.


© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.