0
0
CsharpHow-ToBeginner · 3 min read

How to Use string.Join in C# to Combine Strings

Use string.Join in C# to combine elements of a string array or list into one string separated by a specified delimiter. The syntax is string.Join(separator, values), where separator is the string placed between elements and values is the collection to join.
📐

Syntax

The string.Join method combines multiple strings into one, separated by a specified string.

  • separator: The string to insert between each element (like a comma or space).
  • values: The array or list of strings to join together.
csharp
string.Join(string separator, IEnumerable<string> values);
💻

Example

This example shows how to join an array of words into a single sentence separated by spaces.

csharp
using System;

class Program
{
    static void Main()
    {
        string[] words = { "Hello", "world", "from", "C#" };
        string sentence = string.Join(" ", words);
        Console.WriteLine(sentence);
    }
}
Output
Hello world from C#
⚠️

Common Pitfalls

Common mistakes include:

  • Using null as the separator, which throws an exception.
  • Passing a collection with null elements, which are treated as empty strings.
  • Confusing string.Join with concatenation without separators.
csharp
using System;

class Program
{
    static void Main()
    {
        string[] items = { "apple", null, "banana" };
        // Null elements become empty strings
        string result = string.Join(", ", items);
        Console.WriteLine(result); // Output: apple, , banana

        // Wrong: separator is null - throws ArgumentNullException
        // string error = string.Join(null, items);
    }
}
Output
apple, , banana
📊

Quick Reference

ParameterDescription
separatorString placed between each element in the result.
valuesArray or list of strings to join.
Return valueA single string with all elements joined by the separator.

Key Takeaways

Use string.Join to combine string arrays or lists with a separator.
The separator can be any string, like a comma, space, or dash.
Null elements in the collection become empty strings in the result.
Passing null as the separator causes an error.
string.Join is useful for creating readable strings from collections.