TOC

The community is working on translating this tutorial into Swedish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Operators:

The String Interpolation Operator

Elsewhere in this tutorial, you'll find a lengthy description of the string data type, because dealing with text is such an important task. In this article we'll focus on a special operator for working with strings, allowing you to do quite a few extra tricks when declaring strings. It's called string interpolation (introduced in C# 6.0) and it will allow you to place special markers in your string, which the interpreter will later replace with the relevant values. It works much like the String.Format() method we already discussed, but the syntax is more readable and convenient.

String Interpolation can be achieved very easily - just prefix the string with a $ character. As always, we'll jump straight to an example:

string name = "John Doe";
int age = 42;

Console.WriteLine(name + " is " + age + " years old");
Console.WriteLine($"{name} is {age} years old");

In the last two lines, we do the exact same thing: first in the traditional way, where we concatenate a string using our two variables, and then using string interpolation. Notice how it allows us to inject variables directly into the string by surrounding it with curly braces. And even though this happens inside a string, the compiler will actually check the variables you're trying to inject!

Also, the variables you use doesn't have to be simple types - you can use properties from complex objects as well, just like you could if you were doing regular string concatenation. Here's an example:

var user = new
{
    Name = "John Doe",
    Age = 42
};
Console.WriteLine($"{user.Name} is {user.Age} years old");

Format Strings

By default, the variables you include will be turned into the required string representation by calling the ToString() method on them. But sometimes you might be looking for a bit more control over how each variable is displayed, and fortunately, this is very simple to do, thanks to format strings. Simply put a colon (:) after the variable and then enter a format string to be used, like in this example:

double daysSinceMillenium = (DateTime.Now - new DateTime(2000, 1, 1)).TotalDays;  
Console.WriteLine($"Today is {DateTime.Now:d} and {daysSinceMillenium:N2} days have passed since the last millennium!");

The result will look something like this, depending on your system settings for dates and numbers:

Today is Friday, June 29, 2018 and 6,754.49 days have passed since the last millenium!

Notice how the date is represented in the long date format (as specified with the "D" format string) and the number is nicely formatted with thousand separators and two decimal numbers, thanks to the "N2" numeric format string.

If you want even more control, you can change from the default format strings to custom format strings, e.g. for dates:

Console.WriteLine($"Today is {DateTime.Now:yyyy-MM-dd}");

There are many more ways of formatting a DateTime, that you may use in an interpolated string. For all the options, please consult the documentation.

Beyond variables

Now we have included variables and even properties of objects in our strings and we have seen how easy we can format the resulting strings. But string interpolation goes beyond that, because you can actually have entire C# expressions inside your strings, as long as they result in something that can be appended to a string. A great example of that is the classic "with or without the ending s"-situation, where you have to create a string that's either "1 year old" or "2 years old". You can do that directly with string interpolation, simply by using the ternary operator inside the string:

string name = "John Doe";
int age = 42;

Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old");

Notice how I have inserted a simple if-then-else statement into the string, inside a set of parentheses. We can do that because the result of the expression is a string - either an empty one or an "s". You can do math as well:

Console.WriteLine($"5 + 5 * 2 = {((5 + 5) * 2)}");

Again, as long as the result of the expression can be turned into a string, you can use it within your interpolated string.

String Interpolation & Escaping

You won't have worked with string interpolation for long before a very obvious question comes to mind: How can I include characters which have a specific meaning, e.g. curly braces, and have them treated literally? The answer to that is usually escaping - the act of prefixing/postfixing the character with another character, to negate the special purpose. This is true for string interpolation as well, where curly braces should be written twice if you want them to be treated literally, like this:

Console.WriteLine($"Insert {name} between curly braces: {{name here}}");

The result:

Insert John Doe between curly braces: {name here}

Summary

If you have ever looked at classical string concatenation and thought of it as too clumsy, you'll love string interpolation! It was introduced in C# version 6.0 and allows you to write text which includes variables in a very natural and easy-to-read way. They're also really cool in allowing you to integrate expressions directly into the strings, but be careful - at a certain point, your interpolated string might be so advanced that it becomes harder to read than the alternatives.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!