String Interpolation

String interpolation or interpolated strings allows you to specify expressions right within a string literal for better readability. The string literal will serve as a template containing interpolation expressions that will be replaced with values that resulted in those expressions. Gone are the days of concatenating string literals and expressions into a single string or using string.Format method. Note that string interpolation is a new feature of C# 6 and will not work with earlier versions.

Here is the simplest syntax for using string interpolation.

$"some text {expression} some other text"

To use string interpolation, we prepend any string with a dollar sign ($). Inside the string, we provide one or more interpolation expressions which are identified by enclosing them in a pair of curly braces. Expressions can be a variable or an operation against one or more variables. Anything inside the interpolation expression will be evaluated. The result of the expression will be converted to string using its ToString() method. The final resulting string will then replace the interpolation expression inside the string. If you want to render curly braces, then use double curly braces instead ({{ and }}).

Here is a simple example of using string interpolation.

public class Program
{
    public static void Main(string[] args)
    {
        string message = "Hello World";

        string interpolatedString = $"The message is {message}";

        Console.WriteLine(interpolatedString);
    }
}

Example 1 – Using String Interpolation

The message is Hello World

Line 5 declares a string variable that we will interpolate or insert into a string. Line 7 shows string interpolation in action. We declare a variable that will hold the result of the interpolated string and assign it with this new syntax of prepending a string with a $ sign. Inside the string, the name of the variable was enclosed inside a pair of curly brackets. The value of the variable is used to to replace the interpolation expression.

Here is another example containing multiple interpolation expressions.

public class Program
{
    public static void Main(string[] args)
    {
        string firstName = "John";
        string lastName = "Smith";
        int age = 20;

        Console.WriteLine($"His name is {firstName} {lastName} and his age is {age}.");
    }
}

Example 2 – Example of Multiple Interpolation Expressions

His name is John Smith and his age is 20.

Example 2 shows an example of multiple interpolation expressions. We also used a variable that is not string, and the compiler will just use its ToString() method to determine its string representation.

Example 3 how we can pretty much use any valid C# expressions as interpolation expression.

namespace StringInterpolation
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int num1 = 10;
            int num2 = 20;
            string message = "hello world";
            Person person = new Person { FirstName = "John", LastName = "Smith" };
            
            Console.WriteLine($"The sum of num1 and num2 is {num1 + num2}");
            Console.WriteLine($"num1 less 1 is {num1 - 1}");
            Console.WriteLine($"num2 divided by num1 is {num2 / num1}");

            Console.WriteLine($"num1 is equal to num2? {num1 == num2}");

            Console.WriteLine($"{message} in all caps is {message.ToUpper()}");
            Console.WriteLine($"num1 added by 100 is {Add100(num1)}");

            Console.WriteLine($"Full name is {person.FirstName + " " + person.LastName}");
        }

        private static int Add100(int number)
        {
            return number + 100;
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Example 3 – Using C# expressions as interpolation expression

The sum of num1 and num2 is 30
num1 less 1 is 9
num2 divided by num1 is 2
num1 is equal to num2? False
hello world in all caps is HELLO WORLD
num1 added by 100 is 110
Full name is John Smith

Lines 12 to 14 demonstrated using simple mathematical expressions as interpolation expression. Line 16 used a conditional expression which will output either true or false. Lines 18 to 19 uses methods and the return value of this methods are used as replacements for the interpolation expressions. Line 21 uses properties of an object and uses traditional concatenation to produce the full name (of course you can use string interpolation here as well).

Formatting Interpolation Expressions


You can format the result of an interpolation expression. We simply use the standard formatters of C#. You specify the format by typing a colon then the format pattern.

$"some text {expression:format} some other text"

Here is an example.

public class Program
{
    public static void Main(string[] args)
    {
        double number = 100.1234;
        DateTime today = DateTime.Now;

        Console.WriteLine($"Formatted to currency: {number:C}");
        Console.WriteLine($"2 decimal places {number:F2}");
        Console.WriteLine($"As percentage: {(number / 100):P}");

        Console.WriteLine($"Current Month {today:MM}");
        Console.WriteLine($"Current Day {today:dd}");
        Console.WriteLine($"Current Hour {today:hh}");

        Console.WriteLine($"Date today is {today:MM/dd/yyyy hh:mm:ss}");
    }
}

Example 4 – Using String Formatters

Formatted to currency: $100.12
2 decimal places 100.12
As percentage: 100.12 %
Current Month 08
Current Day 15
Current Hour 04
Date today is 08/15/2015 04:48:28

For a list of numeric and date format strings, follow these links:

https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Specifying Field Widths


You can also specify field widths which are useful for alignment especially if you want to show the values as separate columns.

$"some text {expression, fieldWidth} some other text"

Here’s a simple example. Using a positive field width will add additional spaces to the right of the string result of the interpolation expression if the result’s length is less than the specified field width. Using a negative field width will add spaces to the left of the string result if the result’s length is less than the field width’s absolute value. The number of added spaces is the difference between the field width and the length of the string result of the interpolation expression.

public static void Main(string[] args)
{
    int number = 100;

    Console.WriteLine("Using field width of 10.");
    Console.WriteLine($"Start {number, 10} End");

    Console.WriteLine("\nUsing field width of -10.");
    Console.WriteLine($"Start {number,-10} End");
}

Example 5 – Using Field Widths

Using field width of 10.
Start 100        End

Using field width of -10.
Start        100 End

In the above case, the length of the string “100” is 3 and the field width is 10. So 7 spaces is added to either right or left for positive and negative field widths respectively. If the length of the string result is higher than the field width, then no space is added at all.

You can also combine both field widths and format strings in an interpolation expression using the following syntax.

$"some text {expression, fieldWidth:format} some other text"

Here’s another example that shows a table of data. This example demonstrates field widths and format strings in interpolation expressions.

using System;
using System.Collections.Generic;

namespace StringInterpolation
{
    public class Program
    {
        public static void Main(string[] args)
        {
            List<Product> products = new List<Product>
            {
                new Product { ID = 1, Name = "Soap", Price = 5 },
                new Product { ID = 2, Name = "Toothpaste", Price = 20 },
                new Product { ID = 3, Name = "Portal Gun", Price = 999999999 }
            };

            // Print the header
            Console.WriteLine($"|{ "Code",-5}|{ "Name",-15 }|{ "Price", 20}|");

            foreach(var p in products)
            {
                Console.WriteLine($"|{ p.ID, -5 }|{ p.Name, -15 }|{ p.Price, 20:C}|");
            }
        }
    }

    public class Product
    {
        public int ID { get; set;}
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

Example 6 – Another String Interpolation Example

|Code |Name           |               Price|
|1    |Soap           |               $5.00|
|2    |Toothpaste     |              $20.00|
|3    |Portal Gun     |     $999,999,999.00|

Line 22 uses a combination of field width and formatter to format the Price column into currency.