OneBite.Dev - Coding blog in a bite size

Combine Two Strings In C#

Code snippet for how to Combine Two Strings In C# with sample and detail explanation

When programming in C#, you may often encounter situations where you need to combine, or concatenate, two different strings. This article provides a simple guide on how you can achieve this using the C# programming language.

Code snippet for Combining Two Strings In C#

Let’s dive straight into the code snippet that demonstrates how to perform this operation:

public class Program
{
    public static void Main()
    {
        string str1 = "Hello";
        string str2 = " World!";
        string result = str1 + str2;
        System.Console.WriteLine(result);
    }
}

When you run this program, it will output Hello World!.

Code Explanation for Combining Two Strings In C#

The above C# program is simple to understand. Here are the steps that it follows:

  1. The Main method is the entry point of our program. This is where our code execution starts.

  2. We declare a string variable str1 and initialize it with the string "Hello".

  3. Subsequently, we declare another string variable str2 and initialize it with the string " World!". Notice that we intentionally put a space before the word World! to neatly space out our final contents when we combine the two strings.

  4. Now, we declare a third string result. We combine str1 and str2 using the + operator and store the result in the result string. This + operator is used for concatenation (joining) of strings in C#.

  5. As the final step, we print the result string to the console using System.Console.WriteLine(result);.

So effectively, the + operator in C# allows us to concatenate, or combine, two strings into one. A common use-case for such an operation would be when generating unique identifiers or messages by combining several strings. Remember, the addition operator (+) with strings doesn’t perform mathematical addition; instead, it joins the strings together in the order given.

And with this, we have successfully combined two strings in C#.

c-sharp