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.

Advertisements

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

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

  1. kaluledison says:

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

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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: