Concatenating strings

C#:
Concatenating strings

How to:

Concatenating strings in C# can be done in several ways:

Using + operator:

string hello = "Hello";
string world = "World";
string concatenated = hello + ", " + world + "!";
Console.WriteLine(concatenated); // Output: Hello, World!

Using String.Concat() method:

string concatenated = String.Concat("Hello", ", ", "World", "!");
Console.WriteLine(concatenated); // Output: Hello, World!

Using StringBuilder for efficiency in loops:

StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(", ");
sb.Append("World");
sb.Append("!");
Console.WriteLine(sb.ToString()); // Output: Hello, World!

Using string interpolation (C# 6.0 and above):

string world = "World";
string concatenated = $"Hello, {world}!";
Console.WriteLine(concatenated); // Output: Hello, World!

Deep Dive

String concatenation isn’t new; it’s been around since the early days of programming. However, the way we do it in C# has evolved. Originally, + was widely used, but it’s not always efficient, especially within loops, because strings in .NET are immutable. Each + operation creates a new string, which can lead to performance issues.

String.Concat() is a direct method call that’s also not loop-friendly but fine for a known, small number of strings.

StringBuilder is the go-to for loop scenarios or when building a string incrementally. Under the hood, StringBuilder maintains a buffer to accommodate additions without creating new strings for each append operation.

String interpolation, introduced in C# 6.0, allows for more readable and maintainable code. It translates into a String.Format() call at compile time but is easier on the eyes and less prone to errors.

Each method has its place: quick concatenations (+), combining a few strings (String.Concat()), heavy-duty string building (StringBuilder), and clean, formatted strings (string interpolation).

See Also