NDepend Blog

Improve your .NET code quality with NDepend

C# String Interpolation Explained

May 14, 2025 4 minutes read

CSharp-String-Interpolation-Explained

C# String Interpolation is a powerful feature that simplifies the syntax for embedding variables and expressions within strings to construct strings dynamically. String interpolation evolved significantly during the last few years. In this post, we’ll explore how to use string interpolation effectively with concise explanations and code samples.

What is String Interpolation?

Introduced in C# 6.0, string interpolation provides a more readable and convenient syntax to create formatted strings compared to traditional methods like String.Format.

String interpolation in C# is denoted by a dollar sign $ followed by a string literal in curly braces {item}. For example:

This program outputs: Hello, my name is John and I am 30 years old.

Notice that Visual Studio, VSCode, and JetBrains Rider highlight interpolation expressions in the editor:

Including Expressions

String interpolation isn’t limited to variables; you can also embed expressions:

This program outputs: Total cost: 32.3892

Conditional Expressions

You can include conditional expressions within the interpolated strings.

Formatting

Interpolation allows for formatting numbers, dates, and more directly with the separator character :.

For example, the program below outputs Pi to three decimal places: 3.142

This program below abides by the currency formatting and outputs: Total cost: $32.29

Here is an example with date formatting that outputs: Current date (custom format): 2024-Apr-17

Alignment

Using the character , you can precise the alignment, for example:

This program outputs:

The alignment number indicates the number of characters allowed for displaying the string. If this number is positive, the string is right-aligned; if negative, it is left-aligned. Should the string exceed the length of the alignment number, the runtime doesn’t truncate it. This can cause misalignment when you display multiple lines.

New Lines in Interpolation Expression

Starting from C# 11, you can incorporate new lines within interpolation expressions to enhance code readability. The example below demonstrates how using new lines can make an expression involving pattern matching clearer:

Escaping Braces

To include literal curly braces in an interpolated string, double the character:

This program outputs: {This message includes 3 curly braces}.

C# 11 introduces raw string literals. If you want to be able to use the characters { and } as-is, the interpolated strings need to be prefixed with $$ and the interpolated expressions need to use double curly braces {{item}}. Here is a short sample program:

This program outputs:

Console-C#11-Raw-Literal-Strings

More than two $ characters can be used to prefix an interpolated string to use a sequence of curly braces as-is as illustrated below:

C#11-Raw-Literal-Strings-and-Interpolation-Strings

String Interpolation And Performance

Before C#10 and .NET 6 string interpolation was based on string.Format(). Concretely this program:

…compiled into this:

This means that the formatting string gets parsed at runtime within the method Format() each time it is called. This necessarily has a performance impact.

Since C#10 and .NET 6 the same interpolated string compiles into this:

The C# compiler eases the workload on the runtime by preprocessing the expressions and their formats within interpolated strings.

The C# compiler uses System.Runtime.CompilerServices.DefaultInterpolatedStringHandler, which internally manages a string buffer similar to StringBuilder. However, it is more efficient because it is declared as a ref struct in the Base Class Library (BCL), allowing data to be stored on the thread’s stack. This use of ref struct prevents unintended heap allocation or lifetime issues. This also allows the safe use of Span<T>, which are likewise defined as ref struct. For a deeper dive into ref struct, see: Managed pointers, Span, ref struct, C#11 ref fields and the scoped keyword.

Prior to C# 6 and .NET 10, formatting through the string $"({X}, {Y})" would have created two temporary strings to represent X and Y as text, and then inserted those strings into the final result, resulting in additional allocations.

The ISpanFormattable interface has been available since .NET 10 to help avoid temporary string allocations. Instead of creating intermediate strings, it allows characters representing values like integers X and Y to be written directly into a destination buffer, forming the final result string efficiently. This interface is implemented by all primitive types (such as int, double, DateTime, etc.), and custom types can also implement it.

For an in-depth coverage of compiler interpolated string handlers you can read String Interpolation in C# 10 and .NET 6 by Stephen Toub.

Conclusion

C# string interpolation offers a clean, readable syntax for incorporating variables and expressions into strings. It is suitable for most use cases and simplifies code, making it easier to read and maintain. Experiment with these examples to better understand and apply string interpolation in your own C# projects.

Leave a Reply

Your email address will not be published. Required fields are marked *