C# string.Join

Join objects together

string.Join combines many strings into one. It receives an array or IEnumerable type and a separator string. It places the separator string between every element of the collection in the returned string.

These C# examples show how to use the string.Join method. Join combines an array of strings into one string.

Example

String type

First we see a basic example of how you can combine strings in an array or List into a new single string with dividing characters in it. The example that follows will produce the output with separating commas.

Program that joins strings [C#]

using System;

class Program
{
    static void Main()
    {
	string[] arr = { "one", "two", "three" };
	Console.WriteLine(string.Join(",", arr)); // "string" can be lowercase, or
	Console.WriteLine(String.Join(",", arr)); // "String" can be uppercase
    }
}

Output

one,two,three
one,two,three
Array type

Description. The first line in Main declares a new string[] array with three elements. The second two lines display the result of String.Join to the screen. You can use uppercase or lowercase String. You do not need to specify a string instance.

Note: string.Join is a static method, meaning it is not called on an instance of string. It concatenates strings together with a separator string in between them.

HTML example

Here we see how you can use string.Join to concatenate strings of HTML. Often with HTML you need a separating tag or element, such as a <br/> tag or horizontal rule. Join solves this problem elegantly because it doesn't insert the separating tag at the end.

Program that joins HTML strings [C#]

using System;

class Program
{
    static void Main()
    {
	// Problem: combine these words into lines in HTML
	string[] dinosaurs = new string[] { "Aeolosaurus",
	    "Deinonychus", "Jaxartosaurus", "Segnosaurus" };

	// Solution: join with break tag.
	string html = string.Join("<br/>\r\n", dinosaurs);
	Console.WriteLine(html);
    }
}

Output

Aeolosaurus<br/>
Deinonychus<br/>
Jaxartosaurus<br/>
Segnosaurus

Description. There is a string[] array declared at the beginning of the code. Those strings are concatenated with Join into four lines of markup in HTML, separated by the BR tag.

string.Join versus append

Question and answer

How is Join different from appending? String.Join is different from appending many strings together in a loop, such as with StringBuilder, because it does not insert the delimiter or separator at the end of the operation. It only inserts the delimiter in between the strings.

Rewrite StringBuilder

Here we see how you can replace confusing code that appends strings in loops with much simpler string.Join code. The string.Join method is often much faster in addition to being simpler. The two methods below, CombineA and CombineB, have the same output.

Program that combines strings with Join [C#]

using System;
using System.Text;

class Program
{
    static void Main()
    {
	string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" };
	Console.WriteLine(CombineA(catSpecies));
	Console.WriteLine(CombineB(catSpecies));
    }

    /// <summary>
    /// Combine strings with commas.
    /// </summary>
    static string CombineA(string[] arr)
    {
	return string.Join(",", arr);
    }

    /// <summary>
    /// Combine strings with commas.
    /// </summary>
    static string CombineB(string[] arr)
    {
	StringBuilder builder = new StringBuilder();
	foreach (string s in arr)
	{
	    builder.Append(s).Append(",");
	}
	return builder.ToString().TrimEnd(new char[] { ',' });
    }
}

Output

Aegean,Birman,Main Coon,Nebulung
Aegean,Birman,Main Coon,Nebulung

Description. As noted, the two methods CombineA and CombineB both concatenate each string into a single string with separators. The species of cats are outputted as a single string. The final method shown above, CombineB, has to use the ToString() and TrimEnd() methods to convert the StringBuilder into the result.

ToString Usage TrimEnd Method

Parameters

You can specify four parameters on string.Join, with the last two being the startIndex and the count. This overload is rarely useful in my experience, but could simplify some code.

MSDN reference

Exceptions

Warning

String.Join can throw three different exceptions: ArgumentNullException, ArgumentOutOfRangeException and OutOfMemoryException. The first two exceptions are possible quite often, and you should be ready for them. The following example shows one possible exception.

ArgumentNullException ArgumentOutOfRangeException OutOfMemoryException
Program that throws exception on Join [C#]

using System;

class Program
{
    static void Main()
    {
	try
	{
	    string bug = string.Join(null, null); // Null arguments are bad
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex);
	}
    }
}

Output

System.ArgumentNullException: Value cannot be null.
Parameter name: value

Description. This code demonstrates what happens when you call string.Join with null parameters. It will throw the ArgumentNullException. Depending on your application, this must be dealt with.

Join List

Please note that this example includes the System.Collections.Generic namespace. In the Main entry point, a List is instantiated with three string literals in it. Next, the string.Join<string> method is invoked: the first argument indicates the separator, and the second argument is a reference to the List instance. The method returns a joined string containing the separator.

Program that joins List of strings [C# .NET 4.0]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Create a List of three strings.
	var list = new List<string>() { "cat", "dog", "rat" };
	// Join the strings from the List.
	string joined = string.Join<string>("*", list);
	// Display.
	Console.WriteLine(joined);
    }
}

Output

cat*dog*rat

Notes. By using this version of the string.Join<string> method, you can reduce copies of your collection before using the Join implementation. For this reason, it is preferable to use this version on your List if you do not have an array of your strings handy.

Benchmark

Performance optimization

Here we test the general performance of string.Join. I wanted to see the ballpark numbers for string.Join to ensure that it doesn't cause a severe slowdown. We see that string.Join performs well and often better than loops. Please see the figures at the top of this article.

Data used in benchmark

string[] arr = { "one", "two", "three", "four", "five" };

Methods that were benchmarked [C#]
    1000000 iterations were tested.

static string CombineA(string[] arr)
{
    return string.Join(",", arr);
}

static string CombineB(string[] arr)
{
    var builder = new System.Text.StringBuilder();
    foreach (string s in arr)
    {
	builder.Append(s).Append(",");
    }
    return builder.ToString(); // Has ending comma [difference]
}

Results

string.Join:                 157 ms [faster]
StringBuilder Append method: 270 ms

Required Join method results

Input:  one
	two
	three
Output: one*two*three

Description. The two methods shown above, CombineA and CombineB, compare string.Join to a StringBuilder loop. They return different strings: CombineA does not have a comma at the end of its result, while CombineB does. Using TrimEnd to remove the comma makes CombineB slower.

Summary

The C# programming language

Here we saw several examples of string.Join in the C# language, using comma-separated values and HTML. Finally I established that string.Join has excellent performance for common usages. We also explored the exceptions you can raise with string.Join.

Convert String Array to String String Type
.NET