Author avatar

Dániel Szabó

The Evolution of String Interpolation

Dániel Szabó

  • Aug 15, 2019
  • 6 Min read
  • Aug 15, 2019
  • 6 Min read
Languages Frameworks and Tools


Printing to your console in any programming language is a common task. You may print simple status messages or the outcome of a specific action it does not matter. What matters is how flexible your printing statements are. It also matters how it fits into the flow of a program. For example, people starting out with C# usually do something like the below example. They get the sum of two variables and print the result to the console.

1int x = 10;
2int y = 20;
3int z = x + y;
4Console.Write("The sum of " + x + " and " + y + " is " + z);

The result is:

1The sum of 10 and 20 is 30

This is perfectly fine, it gets the job done. However, it lacks the elegance and the utilization of the facilities C# provides. This guide will show you how to use string interpolation in C# and let detail the latest and greatest in this aspect.

String interpolation can use three types of variable substitution.

  1. Array access
  2. Expressions
  3. Method calls

String interpolation

The most important aspect of the string interpolation is the $ character. This is the character that notifies the compiler about the special kind of string it is about to compile. Let's take a look at a simple example.

1string where = "Pluralsight";
2string what = "written guides";
3Console.WriteLine($"The {what} at {where} are awesome!");

This gives us the following output on our console!

1The written guides at Pluralsight are awesome!

You can see the elegance, and the lack of + characters to concatenate the variables and the characters I would like to print.

The basic syntax looks like this.

` interpolated ,alignment

1This means that you can either specify a spacing definition, which means you want to have *X* number of characters before the interpolated string, or you can specify a formatter. The formatter comes in handy when you are dealing with, for example, dates. You have a date object and you want to have different formats on the output throughout your entire application, based on the method calls or the section you are currently residing at.
3### Interpolation with Array Elements
5String interpolation allows you to handle arrays and their items as input for the action.
6Let's take a look at the following example.
9int [] even = {2, 4, 6, 8, 10};
10string interpolated = $"These are the even numbers {even[0]}, {even[1]}, {even[2]}, {even[3]}!";

Giving us the following output. The interpolation of an interpolated string.

1These are the even numbers 2, 4, 6, 8!

Indexing into a non-existent element of an error will result in an exception! Interpolation can be nested to the n-th level; there is no limit to how many layers of interpolation you can create!

Interpolation with Expressions

While you can use arbitrary operators in your interpolations, there are some light rules which you need to take into consideration. But you can do pretty much anything you want with this approach. Lets look at an example here.

1int y = 10;
2int x = 30;
3Console.WriteLine($"{x} + {y} = {x + y}");
4Console.WriteLine($"{x} - {y} = {x - y}");
5Console.WriteLine($"{x} * {y} = {x * y}");
6Console.WriteLine($"{x} / {y} = {x / y}");

This gives us the following output!

130 + 10 = 40
230 - 10 = 20
330 * 10 = 300
430 / 10 = 3

When an expression evaluates to null the result is an empty string a.k.a. String.Empty character. If the evaluation is not null the ToString method is called of the resulted type.

Interpolation with Method Calls

The third, and most complex aspect of string interpolation, is done with method calls and their return values. The most important thing is to have a return value from the method which can be interpolated, that's all.

1static int FourthPower(int x)
2	{ return x * x * x * x; }
3static void Main(string[] args)
5    int x = 2;
6    Console.WriteLine($"The {x} to the fourth power equals to: {FourthPower(x)}");

The result looks like this:

1The 2 to the fourth power equals 16

Interpolation with Alignment

This example will show you how you can utilize interpolation with alignment from left to right justification. This comes in handy when you want to create a pretty formatted tabular output and preserve the structure you have in mind.

1var workers = new Dictionary<string, string>()
3    ["John Doe"] = "DevOps Engineer",
4    ["Jane Doe"] = "Network Architect",
5    ["William Doe"] = "Product Manager"
7Console.WriteLine("Colleague and Position list!");
10foreach (var title in workers)
11    Console.WriteLine($"|{title.Key,-15}|{title.Value,20}|");

We create our variable which is a string-based dictionary. Then initialize the values with the key-value pairs of three workers. We have the print statement which allows us to name our table. Then the column names are provided called Worker and Position. The first column is left justified, the second column is right-justified.

Specifying a negative value to the alignment argument of the interpolation makes the interpolated string left-justified. The positive value makes it right justified!

The output we get is a nice looking table with a name.

1Colleague and Position list!
3|Worker         |            Position|
4|John Doe       |     DevOps Engineer|
5|Jane Doe       |   Network Architect|
6|William Doe    |     Product Manager|


I hope this guide provided you with an overview of how string interpolation can aide in the ease of development to your applications, as well as increase transparency and maintainability. Compared to older ways of achieving similar results, it's a big step forward and I encourage you to incorporate this into your applications moving forward. All in all, string interpolation is a very handy tool in a developer's toolbox.