DEV Community

Nick
Nick

Posted on

Concatenate Two Strings in C#

In C#, concatenating two strings can be easily achieved using the + operator or the string.Concat() method. Let's dive into both of these approaches with some code examples.

  1. Using the + operator:
string firstString = "Hello";
string secondString = "World";
string concatenationResult = firstString + " " + secondString;
Console.WriteLine(concatenationResult); // Output: Hello World
Enter fullscreen mode Exit fullscreen mode

In the above code, we have declared two string variables firstString and secondString with values "Hello" and "World" respectively. Then, we used the + operator to concatenate them along with a space in between, saving the result in the concatenationResult variable. Finally, we printed the combined string using Console.WriteLine().

  1. Using the string.Concat() method:
string firstString = "Hello";
string secondString = "World";
string concatenationResult = string.Concat(firstString, " ", secondString);
Console.WriteLine(concatenationResult); // Output: Hello World
Enter fullscreen mode Exit fullscreen mode

Similar to the previous example, here we declared the two string variables firstString and secondString. However, instead of using the + operator, we utilized the string.Concat() method. This method takes individual strings as parameters and joins them together. We passed the firstString, a space string, and the secondString as parameters to string.Concat(), saving the result in concatenationResult variable. Finally, we displayed the concatenated string using Console.WriteLine().

Both of these approaches will yield the same output - "Hello World" in this case. However, it's important to note that the + operator can also be used to concatenate variables of other data types such as integers or floats with strings, which might require some type conversion.

In conclusion, concatenating two strings in C# is quite straightforward. Whether you choose to use the + operator or the string.Concat() method depends on your preference and specific requirements.

Top comments (0)