Dot Net For All

How to Concatenate(add) strings in C#

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.

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#.

string concatenatedString = "This" + "is" + "a" + "concatenated" + "string";

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.

string.Concat("This", "is", "a", "string");

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.

 var myVar = 10;
 var addedString = "This" + "is" + "a" + myVar.ToString() + "concatenated" + "string";

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.

 string.Format("This is a {0:d} string", myVar);

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.

            StringBuilder sb = new StringBuilder();
            sb.Append("This is a string");
            sb.AppendFormat("with some format {0:d}", 10);
            sb.AppendLine();
            sb.Append("And new line");

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.

 

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview