ZetCode

C# string interpolation

last modified January 19, 2024

In this article we show how to do string interpolation in C#.

Strings can be created in two basic ways: with string formatting and string interpolation. In this article we cover the latter.

String interpolation is substitution of interpolated expressions within a string literal with their results. The $ special character prefix identifies a string literal as an interpolated string. The interpolated expressions are delimited with curly brackets.

The interpolated expression consists of the following parts:

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

The interpolationExpression is the expression that produces a result to be formatted. The alignment defines defines the minimum number of characters in the string representation of the result. The formatString indicates how the result will be formatted.

Simple example

In the first program, we create a simple string interpolated strings.

Program.cs
string name = "John Doe";
int age = 34;

Console.WriteLine($"{name} is {age} years old");

DateTime now = DateTime.Now;
Console.WriteLine($"Today is {now.DayOfWeek}, it's {now:HH:mm}");

We have two interpolated strings.

string name = "John Doe";
int age = 34;

We define two variables whose values will be used in the first string.

Console.WriteLine($"{name} is {age} years old");

The interpolated string starts with the $ character. The variables are placed between pairs of curly brackets {}.

$ dotnet run
John Doe is 34 years old
Today is Sunday, it's 22:12

String interpolation alignment

In the next example, we align interpolated strings.

Program.cs
List<User> users =
[
    new ("John", "Doe", 1230),
    new ("Lucy", "Novak", 670),
    new ("Ben", "Walter", 2050),
    new ("Robin", "Brown", 2300),
    new ("Amy", "Doe", 1250),
    new ("Joe", "Draker", 1190),
    new ("Janet", "Doe", 980),
    new ("Albert", "Novak", 1930),
];

foreach (var user in users)
{
    string fname = $"{user.FirstName} {user.LastName}";
    Console.WriteLine($"|{fname, -15}|{user.Salary, 8}|");
}

record User(string FirstName, string LastName, int Salary);

We have a list of users. We print the users to the console. The names are aligned to the left, the salaries to the right.

string fname = $"{user.FirstName} {user.LastName}";

First, we join the first and last names into a full name.

Console.WriteLine($"|{fname, -15}|{user.Salary, 8}|");

Negative alignment value aligns the strings to the left, positive to the right.

$ dotner run 
|John Doe       |    1230|
|Lucy Novak     |     670|
|Ben Walter     |    2050|
|Robin Brown    |    2300|
|Amy Doe        |    1250|
|Joe Draker     |    1190|
|Janet Doe      |     980|
|Albert Novak   |    1930|

Format strings

We can provide a format string after a colon character.

Program.cs
DateTime now = DateTime.Now;

Console.WriteLine($"Short date: {now:d}");
Console.WriteLine($"Long date: {now:D}");
Console.WriteLine($"Short time: {now:t}");
Console.WriteLine($"Long time: {now:T}");
Console.WriteLine($"Month: {now:M}");
Console.WriteLine($"Year: {now:Y}");

The program determines the current datetime. It formats the value using various special formatting characters used for datetime values.

$ dotnet run
Short date: 19. 1. 2024
Long date: piatok 19. januára 2024
Short time: 11:19
Long time: 11:19:22
Month: 19. januára
Year: január 2024

Interpolated strings with newlines

Since C# 11, it is possible to add newlines to the expressions.

Program.cs
List<User> users =
[
    new ("John", "Doe", 1230),
    new ("Lucy", "Novak", 670),
    new ("Ben", "Walter", 2050),
    new ("Robin", "Brown", 2300),
    new ("Amy", "Doe", 1250),
    new ("Joe", "Draker", 1190),
    new ("Janet", "Doe", 980),
    new ("Albert", "Novak", 1930),
];

Console.WriteLine($"User with highest salary:\n{
    users.MaxBy(u => u.Salary)
}");

record User(string FirstName, string LastName, int Salary);

In the program, we add a LINQ expression inside the interpolated expression. The expression spans multiple lines. This can add help readability.

$ dotnet run
User with highest salary:
User { FirstName = Robin, LastName = Brown, Salary = 2300 }

Raw strings

We can also use raw strings, which were introduced in C# 11. Raw strings start and end with a minimum of three double-quote characters. They can contain any text without special escape sequences.

Program.cs
var countries = new Dictionary<string, string>
{
    {"Russia", "Moscow"},
    {"Slovakia", "Bratislava"},
    {"Germany", "Berlin"},
    {"Hungary", "Budapest"},
};

foreach (var (k, v) in countries)
{
    Console.WriteLine($"""The capital of "{k}" is "{v}"  """);
}

We can use double quoutes in raw strings without the need to escape them.

$ dotnet run
The capital of "Russia" is "Moscow"  
The capital of "Slovakia" is "Bratislava"  
The capital of "Germany" is "Berlin"  
The capital of "Hungary" is "Budapest"  

Conditional operator

Since colon has a special meaning in the interpolated expression, we place it inside square brackets () for conditional operator.

Program.cs
var items = new Dictionary<string, int>
{
    {"ring", 2},
    {"lamp", 1},
    {"chair", 3},
    {"coin", 5},
    {"TV", 4},
    {"book", 4},
    {"pen", 1},
};

Console.WriteLine("List of items:");

foreach (var (k, v) in items)
{
    Console.WriteLine($"""{v} {k}{(v == 1 ? "" : "s")}""");
}

In the program, we use the conditional operator inside an interpolated string.

$ dotnet run
List of items:
2 rings
1 lamp
3 chairs
5 coins
4 TVs
4 books
1 pen

Source

String interpolation in C#

In this article we have shown how to do string interpolation in C#.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.