6 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();

Next 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.”.

Finally we have the $ operator in C#6. Here’s an example how it is used.

Let’s start with the following Rockband object:

public class Rockband
{
	public string Name { get; }
	public int NumberOfMembers { get; }
	public decimal ConcertFee { get; }

	public Rockband(string name, int numberOfMembers, decimal concertFee)
	{
		Name = name;
		NumberOfMembers = numberOfMembers;
		ConcertFee = concertFee;
	}

	public string GetFancyName()
	{
		return Name.ToUpper();
	}
}

The fancy name is not too fancy but that’s not important now.

In C# 5 we could use string.Format as follows:

Rockband metallica = new Rockband("Metallica", 4, 50);
string formatExampleOne = string.Format("The band is called {0}, they have the fancy name of {1}, they have {2} members and require {3:c} for a concert."
	, metallica.Name, metallica.GetFancyName(), metallica.NumberOfMembers, metallica.ConcertFee);
Debug.WriteLine(formatExampleOne);

formatExampleOne will be…

The band is called Metallica, they have the fancy name of METALLICA, they have 4 members and require £50.00 for a concert.

The currency will differ depending on the culture settings of the thread the code is running under. The point is that you can add a number of format modifiers such as “:c” for currency. You’ll find a long list of examples here on MSDN.

In C# 6 we can rewrite the above with the ‘$’ operator in front of the string literal and actual C# code within the brackets as follows:

string formatExampleTwo = $"The band is called {metallica.Name}, they have the fancy name of {metallica.GetFancyName()}, they have {metallica.NumberOfMembers} members and require {metallica.ConcertFee:c} for a concert.";

You’ll also get IntelliSense when you type “{metallica. “. You’ll also see that additional modifiers such as the currency modifier are also supported.

View all posts related to string and text operations here.

Advertisement

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

4 Responses to 6 ways to concatenate strings with C# .NET

  1. kaluledison says:

    Thanks Andras for good work, always learning new stuff from you.

  2. Leszek says:

    Thanks for variety of options.
    Definitely missing part with optional concatenating like GetFull Address/Name etc. Where strings in the middle can be nullOrEmpty giving us extra space like: “10 county “.
    Need to check the option with list of strings to concatenate…

  3. Rice says:

    Thank you for that its really helpful. But with sample outputs would be better.

    Thanks,

  4. luciaiorgulescu says:

    The 6th method is called string interpolation.
    Good article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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.

%d bloggers like this: