How to use string interpolation in C# 9

Take advantage of string interpolation to incorporate variable substitution in formatted strings in C#.

How to use string interpolation in C# 9
Getty Images

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.

String interpolation is supported by many programming languages including Python, Perl, PHP, Ruby, Java, Scala, etc. It was introduced in C# in C# 6. This article talks about how we can work with string interpolation in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

We’ll use this console application project to work with string interpolation in the subsequent sections of this article.

Structure of an interpolated string in C#

In programming, an interpolated string is a literal string that contains interpolation expressions. Each time an interpolated string is resolved to a result string, the interpolation expressions are replaced with string representations of the results of the expressions.

An interpolated string starts with the $ symbol. Moreover, there cannot be any space between the $ character and the string literal. The following statement illustrates the syntax of an interpolated expression:

{<interpolationExpression>[,<alignment>][:<formatString>]}

Note that the elements inside the square brackets are optional. The interpolationExpression element represents the expression that produces a result or output string. The alignment element represents a constant expression whose value specifies the minimum number of characters that must be included in the string representation of the expression result when the expression is evaluated. If the value is positive, the string representation is right-aligned; if the value is negative, the string representation is left-aligned. The formatString element, as the name suggests, represents a format string that is appropriate for the result of the expression, i.e. the object being formatted.

Create an interpolated string in C#

When using string interpolation, you must first insert a $ character immediately before the string; then, rather than providing parameters for the format elements individually, those arguments may be embedded directly into the interpolated string.

An interpolation expression is contained inside an opening and closing brace, ({ and }). The following code snippet shows how string interpolation can be used to replace a string literal with text.

var name = "Joydip";
Console.WriteLine($"Hello, {name}");

Now consider the following code snippet:

string productName = "Lenovo Legion Laptop";
int counter = 5;
string output = string.Format("Today, {0} has been sold {1} times.",
                                               productName, counter);

When you run the program, the content of the string object named output at runtime will be this:

Today, Lenovo Legion Laptop has been sold 5 times.

The above code could also be written as:

string productName = "Lenovo Legion Laptop";
int counter = 5;           
string output = $"Today, {productName}, has been sold {counter} times.";

Interpolated strings must be compile-time string literals

Interpolated strings seem like a simple way to create string templates that can evaluate expressions. However, it is essential to realize that string interpolation in C# is merely a syntactic sugar produced by the compiler to create strings dynamically. Remember that the format string must be a static string literal. In other words, your interpolated strings must be available at compile time as string literals.

Use special characters in interpolated strings in C#

Let us now look at how to use special characters in interpolated strings. Consider the following example that illustrates this.

string productName = "Lenovo Legion Laptop";
double price = 1600.00;
Console.WriteLine($"The customer asked, \"What is the price of {productName}?\"");
Console.WriteLine($"The salesman replied saying that the price of {productName} is ${price}.");

As you can see, including special characters is as simple as escaping the special character with a backslash ( \ ).

String interpolation allows you to insert values into a string and control the text formatting of the resulting string as well. Interpolated strings of type string are generally transformed into String.Format method calls. Conversely, if an interpolated string is of type IFormattable or FormattableString, the compiler will call the FormattableStringFactory.Create method.

Using string interpolation can introduce a minor performance degradation. However, recent versions of .NET have been optimized a great deal, and the flexibility that string interpolation provides generally outweighs the performance cost.

Copyright © 2021 IDG Communications, Inc.

How to choose a low-code development platform