A new way to format strings in C# 6
February 22, 2016 Leave a comment
In C# 5 we often format strings with the string.Format function. It requires a format string and then a number of parameters that are passed into the format string. C# 6 has a nice addition which simplifies that syntax.
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 various C# language feature related posts here.