How to Concatenate(add) strings in C#

By | August 17, 2017

All of us work with strings in our projects. And if we are not handling strings in proper way it can be a big bottleneck for performance for your tool. Whatever type of application it is in .NET either windows or web we should be very careful with strings. And to be careful we should know about the basics of strings concatenation.

Become an Expert in Programming and Web Development.View all courses!

You may find the below article useful before reading this article:

Strings in C#

StringBuilder class performance

Now let’s see a string concatenation example in C#.

What do you think is the above method of string concatenation is correct or not?

The above method of concatenating the strings is wrong. And the reason is since strings are immutable every time we are adding two strings we are creating a new string.

In the above code we are creating 10 different strings which can lead to performance bottleneck if we are working with huge number of strings. and garbage collector has to clean all those strings.

How we can create string in more optimal way?

.Net framework provides many better ways to concatenate the strings. Let’s discuss them one by one.

Using String.Concat

In the below code I have use the concat method of the string class to add all the strings.

Using String.Format

In the above example if we using the “+” symbol also the compiler will create an optimized way to add the strings, but what if we have a value in the strings which is assigned at run time.

In the above code we have a variable and we are calling .ToString() for it. Here we will use the String.Format for concatenation. It helps us to place the placeholders.

In the above code we are using format which will insert first parameter into the string with correct format. It won’t convert myVar into a string.

Using StringBuilder class

The last and most efficient way to concatenate strings is using StringBuilder class as shown in the code below.

In the above code I have created a new string with format and carriage returns with the help of StringBuilder class. The class is present in the System.Text namespace.