Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

The Evolution of String Interpolation

This guide will show you how to use string interpolation in C# with Array access, Expressions, and Method calls.

Aug 15, 2019 • 6 Minute Read

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.

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

The result is:

      The 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.

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

This gives us the following output on our console!

      The 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][:formatString]

      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.

      These 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.

      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}");
    

This gives us the following output!

      30 + 10 = 40
30 - 10 = 20
30 * 10 = 300
30 / 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.

      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)}");
}
    

The result looks like this:

      The 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.

      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}|");
    

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.

      Colleague and Position list!

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

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.