Quantcast
Channel: C# – Falafel Software Blog
Viewing all articles
Browse latest Browse all 54

String Interpolation – Day 10 – Visual Studio 2015

$
0
0

Even in the early days of C# there were ways to construct strings that use values from variables using either concatenation or string.Format. After many years with no change in how this is done, C# 6 brings a new feature called String Interpolation that will make it easier to build strings containing variable data.

First, let’s look at what our options were before string interpolation, with either string.Format or concatenation:

[TestMethod]
public void StringFormatAndConcat()
{
    var data = new DemoData() { Id = 100, Name = "David Smith" };

    // string.Format
    var message = string.Format("Id is {0} and Name is '{1}'", data.Id, data.Name);
    Assert.AreEqual<string>("Id is 100 and Name is 'David Smith'", message);

    // concat string
    message = "Id is " + data.Id + " and Name is '" + data.Name + "'";
    Assert.AreEqual<string>("Id is 100 and Name is 'David Smith'", message);
}

While both of these work fine, they each have their downsides: concatenation lets you see your variables inline with the text, but is less readable and more cumbersome because of the added quotes and + symbols; string.Format makes the string itself cleaner and more readable, but it is easy to get your parameters misaligned from the placeholders.

String Interpolation

String Interpolation gives us the best of both concatenation and string.Format: it is easily readable and you can see your variables inline with the text.

To use string interpolation, you simply need to prefix your string literal with a “$” symbol and wrap your variables in curly braces {}. Here’s a simple example:

[TestMethod]
public void SimpleInterpolation()
{
    var data = new DemoData() { Id = 100, Name = "David Smith" };
    var message = $"Id is {data.Id} and Name is '{data.Name}'";
    Assert.AreEqual<string>("Id is 100 and Name is 'David Smith'", message);
}

Format Specifiers

But wait, string.Format lets me use format specifiers to format my value, such as showing currency like:  string.Format(“The total is {0:C}”, totalAmount); which outputs “The total is $109.83”

Yes, we can use format specifiers with string interpolation as well! Here’s an example that formats a date to use the Month/day pattern using {data.Birthdate:M}

[TestMethod]
public void InterpolationWithFormatSpecifier()
{
    var data = new DemoData() { Id = 100, Name = "David Smith", Birthdate = new DateTime(1970, 2, 25)};
    var message = $"Name is '{data.Name}' and Birthday is {data.Birthdate:M}";
    Assert.AreEqual<string>("Name is 'David Smith' and Birthday is February 25", message);
}

Keywords and Conditions with String Interpolation

We can also use other keywords such as the new nameof() keyword to include the variable name without resorting to string literals:

[TestMethod]
public void InterpolationWithNameOf()
{
    var data = new DemoData() { Id = 100, Name = "David Smith" };
    var message = $"{nameof(data.Id)} is {data.Id} and {nameof(data.Name)} is '{data.Name}'";
    Assert.AreEqual<string>("Id is 100 and Name is 'David Smith'", message);
}

You can even use null conditional and null coalescing operators within the placeholders if you want to handle null values in your variables:

[TestMethod]
public void InterpolationWithNullConditional()
{
    DemoData data = null;
    var message = $"Id is {data?.Id ?? 0} and Name is '{data?.Name ?? @"NONE"}'";
    Assert.AreEqual<string>("Id is 0 and Name is 'NONE'", message);
}

Even though string interpolation isn’t anything earth-shattering, it can make your string formatting code more readable and maintainable.

Try out it for yourself using my sample project on GitHub.

The post String Interpolation – Day 10 – Visual Studio 2015 appeared first on Falafel Software Blog.


Viewing all articles
Browse latest Browse all 54

Trending Articles