Author avatar

Dániel Szabó

The Evolution of String Interpolation

Dániel Szabó

  • Aug 15, 2019
  • 6 Min read
  • 20 Views
  • Aug 15, 2019
  • 6 Min read
  • 20 Views
Languages Frameworks and Tools
C#

Introduction

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.

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

The result is:

1
The sum of 10 and 20 is 30
bash

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.

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

This gives us the following output on our console!

1
The written guides at Pluralsight are awesome!
bash

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

1
2
3
4
5
6
7
8
9
10
11
This 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.

### Interpolation with Array Elements

String interpolation allows you to handle arrays and their items as input for the action.
Let's take a look at the following example.

```csharp
int [] even = {2, 4, 6, 8, 10};
string interpolated = $"These are the even numbers {even[0]}, {even[1]}, {even[2]}, {even[3]}!";
Console.WriteLine($"{interpolated}");

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

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

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.

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

This gives us the following output!

1
2
3
4
30 + 10 = 40
30 - 10 = 20
30 * 10 = 300
30 / 10 = 3
bash

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.

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

The result looks like this:

1
The 2 to the fourth power equals 16
bash

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.

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

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.

1
2
3
4
5
6
Colleague and Position list!

|Worker         |            Position|
|John Doe       |     DevOps Engineer|
|Jane Doe       |   Network Architect|
|William Doe    |     Product Manager|
bash

Conclusion

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.

0