C# String Concatenation - Complete Guide
Introduction to String Concatenation
String concatenation in C# is the process of combining multiple strings into one. There are several approaches to concatenation, each suited for different scenarios.
Choosing the right method affects readability and performance, especially when handling large text or performing repeated concatenations.
Concatenation Methods
C# offers multiple approaches for concatenating strings, ranging from simple operators to optimized classes like StringBuilder.
Example
using System;
using System.Text;
namespace StringConcatenationExample
{
class Program
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
int age = 30;
// 1. + operator
string fullName1 = firstName + " " + lastName;
Console.WriteLine($"Using + operator: {fullName1}");
// 2. string.Concat
string fullName2 = string.Concat(firstName, " ", lastName);
Console.WriteLine($"Using string.Concat(): {fullName2}");
// 3. string.Join
string fullName3 = string.Join(" ", firstName, lastName);
Console.WriteLine($"Using string.Join(): {fullName3}");
// 4. StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append(firstName).Append(" ").Append(lastName).Append(", Age: ").Append(age);
Console.WriteLine($"Using StringBuilder: {sb.ToString()}");
// 5. Interpolation
string interpolated = $"{firstName} {lastName}, Age: {age}";
Console.WriteLine($"Using interpolation: {interpolated}");
}
}
}
Output
Using + operator: John Doe Using string.Concat(): John Doe Using string.Join(): John Doe Using StringBuilder: John Doe, Age: 30 Using interpolation: John Doe, Age: 30
Performance Considerations
Some concatenation methods are more efficient than others. The + operator creates new strings for each operation, which is costly in loops. StringBuilder and string.Concat are much faster for bulk concatenations.
Example
using System;
using System.Diagnostics;
using System.Text;
namespace ConcatenationPerformanceExample
{
class Program
{
static void Main(string[] args)
{
const int iterations = 10000;
// + operator
Stopwatch sw1 = Stopwatch.StartNew();
string result1 = "";
for (int i = 0; i < iterations; i++)
result1 += "a";
sw1.Stop();
// StringBuilder
Stopwatch sw2 = Stopwatch.StartNew();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++)
sb.Append("a");
string result2 = sb.ToString();
sw2.Stop();
// string.Concat with array
Stopwatch sw3 = Stopwatch.StartNew();
string[] arr = new string[iterations];
for (int i = 0; i < iterations; i++)
arr[i] = "a";
string result3 = string.Concat(arr);
sw3.Stop();
Console.WriteLine($"Performance for {iterations} concatenations:");
Console.WriteLine($"+ operator: {sw1.ElapsedTicks} ticks");
Console.WriteLine($"StringBuilder: {sw2.ElapsedTicks} ticks");
Console.WriteLine($"string.Concat: {sw3.ElapsedTicks} ticks");
}
}
}
Output
Performance for 10000 concatenations: + operator: 158724 ticks StringBuilder: 342 ticks string.Concat: 125 ticks