String Interpolation in C# 6

We regularly use string.Format or string.Concat or “+” operator to do all kinds of string manipulations.

public class Person
{
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }
}

public void PrintPersonName(Person person)
{
    Console.WriteLine(string.Format("Full Name: {0} {1} {2}", person.FirstName, person.LastName, person.MiddleInitial));
}

String.Format and its cousins are very versatile, but their use is somewhat clunky and error prone. Particularly unfortunate is the use of numbered placeholders like {0} in the format string, which must line up with separately supplied arguments.

This creates new problems:

  • You have to maintain the index yourself. If the number of arguments and index are not the same, it will generate error.
  • If you need to add a new item to the string (not to the end), you have to update the whole indexing number.

For those reasons, we should use C# 6 new feature String interpolation.

public void PrintPersonNameNewWay(Person person)
{
            Console.WriteLine($"Full Name: {person.FirstName} {person.LastName} {person.MiddleInitial}");
}

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.  In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

Advertisements

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