In C#, you can concatenate two strings using the +
operator or the String.Concat
method. Here's an example of both approaches.
Using the +
Operator
string str1 = "Hello";
string str2 = "World";
// Concatenate using the + operator
string result = str1 + " " + str2;
Console.WriteLine(result); // Output: Hello World
Using String.Concat
Method
string str1 = "Hello";
string str2 = "World";
// Concatenate using String.Concat method
string result = string.Concat(str1, " ", str2);
Console.WriteLine(result); // Output: Hello World
Using String.Join
Method
If you need to concatenate multiple strings, you can use String.Join.
string str1 = "Hello";
string str2 = "World";
// Concatenate using String.Join method
string result = string.Join(" ", str1, str2);
Console.WriteLine(result); // Output: Hello World
String Interpolation (C# 6 and later)
string str1 = "Hello";
string str2 = "World";
// Concatenate using string interpolation
string result = $"{str1} {str2}";
Console.WriteLine(result); // Output: Hello World
Choose the method that fits your coding style and the requirements of your application. The +
operator is commonly used for simple concatenation, while String.Concat
and String.Join
provide more flexibility in handling multiple strings or collections of strings. String interpolation is a concise and readable way to concatenate strings introduced in C# 6.