5 ways to concatenate strings with C# .NET

There are multiple ways to build a string out of other strings in .NET. Here come 5 of them.

Let’s start with the most obvious one that language learners encounter first, i.e. concatenation done by the ‘+’ operator:

string concatenatedOne = "This " + "is " + "a " + "concatenated " + "string.";

The string class offers a static method called Concat where you can pass in an IEnumerable of string as follows:

IEnumerable<string> strings = new List<string>() {"This ",  "is ", "a ", "concatenated ", "string." };
string concatenatedTwo = string.Concat(strings);

There’s another static method called Join in the string class which can join strings. The first parameter in the following overload is the separator which will be added in between the individual string elements:

string concatenatedThree = string.Join(" ", "This", "is", "a", "concatenated", "string.");

The StringBuilder class offers a very flexible way to append strings to each other:

StringBuilder sb = new StringBuilder();
sb.Append("This ").Append("is ").Append("a ").Append("concatenated ").Append("string.");
string concatenatedFour = sb.ToString();

Lastly we have the string.Format method where you can supply a format as the first parameter and a params array of the elements that will be substituted into the format:

string concatenatedFive = string.Format("{0} {1} {2} {3} {4}", "This", "is", "a", "concatenated", "string.");

All 5 string variables will have the value “This is a concatenated string.”.

View all posts related to string and text operations here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to 5 ways to concatenate strings with C# .NET

  1. Hardik says:

    Its very helpful.. Thanks

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.