Concatenate strings in C#
This post will discuss how to concatenate strings in C#.
1. String concatenation using (+)
String concatenation in C# is done using the + operator. We can use this for concatenating two or three strings.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string x = "Hello"; string y = "World"; string concat = x + y; Console.WriteLine(concat); } } |
2. Using String.Concat() method
A simple and fairly efficient solution to concatenate two or more strings using the String.Concat() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string x = "Hello"; string y = "World"; string concat = String.Concat(x, y); Console.WriteLine(concat); } } |
3. Using StringBuilder.Append() method
StringBuilder.Append method can be used to append multiple strings effectively. This is a preferred solution over the + operator for concatenating more than three strings.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Text; public class Example { public static void Main() { string x = "Hello"; string y = "World"; string concat = new StringBuilder().Append(x).Append(y).ToString(); Console.WriteLine(concat); } } |
4. Using String.Join() method
The following code example demonstrates how to use the String.Join() method for concatenating multiple strings using an empty string as a separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string x = "Hello"; string y = "World"; string concat = String.Join(String.Empty, new string[] { x, y }); Console.WriteLine(concat); } } |
5. Using String.Format() method
One can use String.Format() method for concatenating multiple strings with one another, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string x = "Hello"; string y = "World"; string concat = String.Format("{0}{1}", x, y); Console.WriteLine(concat); } } |
6. String Interpolation
Starting with C# 6, one can use String interpolation ($), which provides a convenient syntax for converting an integer to a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string x = "Hello"; string y = "World"; string concat = $"{x}{y}"; Console.WriteLine(concat); } } |
That’s all about concatenating strings in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)