What is String Interpolation in C#?

01 August 2021 at 02:00 by ParTech Media - Post a comment

You would have come across various instances and applications that use string interpolation. But, you wouldn’t have recognized it, as it's something that happens in the background. For example, if you log in to your favorite e-commerce website, OTT platform, online ticketing booking sites, banking websites, etc., you are mostly shown with a message such as - ‘Welcome back Ruud’.

Similarly, when you log out and log in with some other id, the corresponding name is displayed on the screen. Now, note that this is achieved via two parts of the welcome note, one being the static part and the other, the dynamic part.

It is quite obvious that over here - ‘Welcome back’ is the static text while the name that follows it is the dynamic text. This is a classic example of the string interpolation technique. And this is a very important and basic feature that a developer must know.

Let’s see in detail everything about this popular feature and how it works in C#.

Table of contents

  1. Basics of String Interpolation
  2. Examples of String Interpolation
  3. Capabilities of String Interpolation
  4. Conclusion

Basics of String Interpolation

Before we understand string interpolation, let's look at composite formatting, which is the foundation principle on top of which the String interpolation is built in C#. Composite formatting is the conventional way of constructing the result text with both static and dynamic data.

Composite formatting consists of static text mixed with indexed placeholders. It takes a list of objects as input, which then get replaced in the indexed position in the sequential order.

For example -

var name = “Max”;

var formattedData = String.Format(“Hi {0}. The current date time is {1}”, name, DateTime.Now.ToString());

In the above example, index 0 corresponds to the variable - ‘name’ and index 2 corresponds to the DateTime part.

But, consider a paragraph that has a lot of dynamic data that needs to be added to the runtime,

For example -

var formattedData = String.Format(“Hi {0}, Welcome to {1}. The current date time is {1}. And the weather forecast for today is {2}. Have a pleasant stay. Reach us at {3} ”, name, countryName, DateTime.Now.ToString(), weatherData, contactNumber.ToString());

Here, the dynamic data that has to be replaced is split across the entire paragraph and it becomes difficult for the developers to read through to understand what variable is being passed at which position. This might lead to the inappropriate positioning of data (say weather and contact number get interchanged).

To make it more readable and make it easy for the developers, string interpolation was created. It is available from C# version 6.

Examples of String Interpolation

String interpolation is generally represented by $ preceding the string literal. There cannot be any space between $ and “(double quotes). This enables the developers to add the necessary dynamic data (variables) on the go rather than adding them all together at the end, unlike composite formatting.

Here, the variable that holds the value is being denoted within braces { } inside the double-quotes. Braces also support null values.

The difference between composite and string interpolation can be understood with the help of the example below -

using System;  

namespace PARTECHStringInterpolation

{  

  class PARTECHStringInterpolation  

  {  

​    public static void Main()  

​    {  

​      string name = "Max";  

​      int age = 20;  

​      // Composite format 

​      Console.WriteLine("Name = {0}, age = {1}", name, age);  

​      // String Interpolation  

​      string s1  = $"{name} is {age} years old.";  

​      Console.WriteLine(s1);  

​    }  

  }  

} 

Let's understand the syntax of interpolation.

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

Here, the contents inside the square brackets are optional (i.e alignment and format string are optional). The formatted data string value is a simple example of just interpolation expression.

Example with only interpolation expression.

var name = “Max”;

var formattedData = $“Hi { name }. The current date time is { DateTime.Now.ToString() }”); 

This is the transformed code of the composite formatting to String interpolation. Does it look easy to read and implement?

Example for the usage of interpolation expression and alignment.

Console.WriteLine($"{Math.PI,10} - Formatting of pi without decimal limitation.");

Output - 3.14159265358979 - Formatting of pi without decimal limitation.

Here, Math.PI is an in-built property in C#, which holds the value of pi. And the number 10 denotes how far it is aligned towards the right from the center (where 0 indicates the center, the negative values indicate left-aligned, and positive values indicate right-aligned).

Example for the usage of interpolation expression, alignment, and format string

Console.WriteLine($"{Math.PI,10:F3} - with only three decimal digits of the pi number.");

Output - 3.141 - with only three decimal digits of the pi number.

Here, F3 denotes the three numbers of decimal values that are needed to print pi.

Capabilities of String Interpolation

Adding special characters in string interpolation

There are two ways to add special characters while using string interpolation.

var path = $”C://Users//{username}//downloads”;

Here, the first slash serves as an escape sequence for the following one.

The other way of doing it is by adding @ before or after the $ symbol while framing the interpolated string.

For Example - $@”C:/Users/{username}/downloads”;

This feature of handling special characters using @ is available from C# version 8.

To format a multiline string, use @ followed by $.

{

Console.WriteLine($@"Hi {name}, Today is {date.DayOfWeek} and it's {date:HH:mm} now.

Welcome to PARTECH

Your location is {location}");

} 

Usage of ternary operation inside interpolation expression

var rand = new Random();

for (int i = 0; i < 5; i++)

{

  Console.WriteLine($"Sample Result: *{(rand.NextDouble() > 0.5 ? "Value is higher" : "Value is lesser")}*");

}

Here, in the above example, the condition inside the interpolation expression gets executed at run time, based on which the value is being displayed.

During the compilation time, the string interpolations are transformed to String.Format, which is in turn converted to String.Concat. In the end, it will be concatenated.

The string interpolation technique can also be used with C# culture.

Conclusion

This blog gives you a high-level idea about how composite formatting and string interpolation is defined and the different options that are available in string interpolation. From the examples that we have gone through, it is clear that String interpolation provides an upper hand over composite formatting for the developers to format texts.

Latest