Csharp (C #) has predefined special identifiers that modify the element to which it precedes, such as a string, an identifier or the name of an attribute.
In Csharp 6 was introduced the special identifier “$” that marks a string as interpolated, that is, it can contain expressions of the language. In other words, it is a way to inject values into a string.
Let’s see an example with a formatted string and another interpolated to see their differences:
Although the same result is produced, it is easier to read and write an interpolated string, without mentioning we write less code, and remember: les code is better code.
To insert special characters such as double quotes or the backslash, the most elegant way to do it is to use the verbatim identifier “@” just after the interpolated string identifier “$”, as we see in the following example:
Another way to do it is to use the backslash “\” as escape character, let’s see:
In the case that we want to show keys curly brackets it will be necessary to place them twice, as follows:
Here you can see more about String Escape Sequences.
It is also possible to apply formats to a string in an interpolated expression. Let’s see somes examples:
You can see more about Formatting Types in .NET.
In an interpolated string we can use the ternary conditional operator “?:” to make a decision as we see in the example:
We can see that we must enclose the conditional part of the logical expression in parentheses so that it works.
You can learn more about the ternary operator by clicking here.
The string interpolation is a very easy and precise way to inject variable values in a string, as well as to write, read and understand, we can adapt them to specific formats and use conditions in it.