String Concatenation in C#

In this post, I am going to write about the different ways you can concatenate strings in C# language and generate the results you want. Each one of these ways has its own use cases, and we will discuss which one and when should be used to be more effective and useful.

There are 6 ways that you can concatenate strings in C# language, and those 6 are:

  1. String Interpolation
  2. + Operator 
  3. String.Format() method
  4. String.Join() method
  5. String.Concat() method
  6. StringBuilder class


String Interpolation

This syntax has been introduced at C# 6.0, it’s a clean way of adding string variables in the middle of a text. This syntax defined by adding a $ before string and using {} around variables to include them in the string. It will be much more understandable when you see that in the example. This way of concatenation is more readable by developers.


+ Operator 

The + operator is the fastest and simplest way to do a string concatenation, the best place to use this way is when you have very straightforward concatenation, or when you have a string being generated in a loop where you can keep adding to the existing string variable.


String.Format() Method

This method exist in C# language for formatting a string. Text concatenation is one of the many string manipulations that you can do using this method. The best use of this function is when you have data like money or date and you want to format them in a specific way. Let’s see an example that how we can use this.


String.Join() Method 

This method can be used to concatenate members of a collection. You will need to pass your collection and the separator you want to be used for separating the members in the result. There is an overload for this method that you can specify the starting and ending index that you want to be included in the concatenation.


String.Concat() Method 

This method can concatenate two strings or a collection of strings without a separator.


StringBuilder Class

StringBuilder is recommended for heavy string manipulation codes. String object is immutable, which means that every time you do a manipulation a new string object will be generated in the memory. That will consume a lot of memory if you do a lot of concatenations in your code and will not be efficient at all. Therefore, C# has the StringBuilder class under the System.Text namespace which can be used for this type of scenarios and will keep all string in one memory location.



All examples in one place:


StringConcatenation Console