OneBite.Dev - Coding blog in a bite size

Concatenate A String In C#

Code snippet for how to Concatenate A String In C# with sample and detail explanation

In programming languages like C#, string concatenation is a common practice to merge or combine two or more strings into one. The main purpose of concatenating strings is to create a single string that includes the contents of multiple string variables.

Code Snippet: String Concatenation in C#

string firstName = "John ";
string lastName = "Doe";

// Concatenate two strings
string fullName = firstName + lastName;
Console.WriteLine(fullName);

This code sample provides a basic illustration of how you can concatenate strings in C#.

Code Explanation for String Concatenation in C#

In the given code snippet:

  1. We first declare two string variables firstName and lastName, giving them values “John” and “Doe” respectively.
  2. The third line combines these strings using the ’+’ operator, which is the most straightforward way to concatenate strings in C#. The ’+’ operator can be used to concatenate two or more string literals, string variables, or a combination of both.
  3. The resulting concatenated string is stored in the variable fullName.
  4. In the final line, the Console.WriteLine() method is used to print the fullName to the console. This will output “John Doe”.

It’s that simple! Remember, however, that string concatenation using the ’+’ operator can result in performance issues if done repetitively within large loops. In such cases consider using other methods like StringBuilder, String.Concat, or String.Join, depending on the situation.

c-sharp