How to Join Strings in C#: Simple Methods and Examples
string.Join method, which combines an array or list of strings with a separator. Alternatively, you can use the + operator or string interpolation to concatenate strings directly.Syntax
The main way to join multiple strings in C# is using string.Join(separator, values). Here, separator is the string placed between each value, and values is an array or collection of strings to join.
You can also join strings by using the + operator or $"{variable}" for interpolation.
string result = string.Join(", ", new string[] {"apple", "banana", "cherry"}); string combined = "Hello" + " " + "World!"; string name = "Alice"; string greeting = $"Hello, {name}!";
Example
This example shows how to join a list of fruits into a single string separated by commas using string.Join. It also shows string concatenation and interpolation.
using System; class Program { static void Main() { string[] fruits = { "apple", "banana", "cherry" }; string joinedFruits = string.Join(", ", fruits); Console.WriteLine(joinedFruits); string hello = "Hello" + " " + "World!"; Console.WriteLine(hello); string name = "Alice"; string greeting = $"Hello, {name}!"; Console.WriteLine(greeting); } }
Common Pitfalls
One common mistake is trying to join strings without using string.Join for collections, which leads to printing the collection type instead of the joined string. Another is forgetting to add a separator, which can make the output hard to read.
Also, using + repeatedly in loops can be inefficient for large numbers of strings; string.Join or StringBuilder is better in those cases.
/* Wrong way: printing array directly */ string[] words = { "one", "two", "three" }; Console.WriteLine(words); // Prints System.String[] /* Right way: use string.Join */ Console.WriteLine(string.Join(", ", words)); // Prints one, two, three
Quick Reference
- string.Join(separator, values): Joins multiple strings with a separator.
- + operator: Concatenates two or more strings.
- String interpolation ($"..."): Embeds variables inside strings easily.