Using Interpolated Strings

I was code reviewing one of my developers at work the other day when I noticed he had used a $ at the start of a string in C#. Immediately I thought "hang on this isn't JQuery, its C#!".

After understanding what the $ represents for strings I thought it must be a little known feature of C# which would make a good useful Tip article.

The $ signifies what is known as an Interpolated String. Sounds complicated but I can assure you it's very simple. The examples below will reveal all. It was added in C# version 6.0 back in 2015.

In its most basic form, an Interpolated string simply embeds a C# variable into the string using curly braces. The key is to ensure you match exactly the variable name.

This first example shows how to use a single variable as an Interpolated String.

[TestMethod]
public void TestInterpolatedStrings_1()
{
    string _name = "JGilmartin";
    string InterpolatedString = $"hello my name is {_name}";

    Assert.IsTrue(InterpolatedString == "hello my name is JGilmartin");
}

Ok cool, saves having to use Srtring.Format which is nice!

Lets have a look at a more complex example. The string I want to output is the full date in the following format.

"Today is Sunday the 26th of February 2017"

Let's have a look at how to do that. I have created a private method to return the day prefix such as 2nd, 3rd, ect.

[TestMethod]
public void TestInterpolatedStrings_2()
{
    DateTime now = DateTime.Now;

    string DayName = now.DayOfWeek.ToString();
    string DayOfMonth = GetDaySuffix(now.Day);
    string Month = now.ToString("MMMM");
    string year = now.Year.ToString();

    string InterpolatedString = $"Today is {DayName} the {DayOfMonth} of {Month} {year}";

    Assert.IsTrue(!String.IsNullOrEmpty(InterpolatedString));
}

private string GetDaySuffix(int day)
{
    switch (day)
    {
        case 1:
        case 21:
        case 31:
            return day + "st";
        case 2:
        case 22:
            return day + "nd";
        case 3:
        case 23:
            return day + "rd";
        default:
            return day + "th";
    }
}

The final point to note is that you can call functions on the variables within Interpolated strings, so I can set .ToUppper() directly in the string, see below.

string InterpolatedString = $"Today is {DayName.ToUpper()} the {DayOfMonth.ToUpper()} of {Month.ToUpper()} {year}";

From now on I will be using $"" for string format and manipulation in my code from now on. Give it a try.


JGilmartin Profile Image

JGilmartin

Technical Architect at Pinewood Technologies

Rating: 2890

C# Expert

Offline


Useful Tip Statistics
  • Views: 566
  • Comments: 0
  • Author: JGilmartin (2890)
  • Date: 26/2/2017 14:30
Tags
C#

© 2016 - 2018 - IntermittentBug