NDepend Blog

Improve your .NET code quality with NDepend

C# String Interpolation Explained

April 17, 2024 3 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 allotted 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.

Also the C# compiler relies on System.Runtime.CompilerServices.DefaultInterpolatedStringHandler that maintains internally a string buffer similarly to StringBuilder. But it is more efficient due to being declared as a ref struct in the Base Class Library (BCL). The use of ref struct allows it to leverage the managed pointer capabilities of the runtime, enhancing performance. This design is also seen in types like Span<T>, which are also defined as ref struct.

For a deeper understanding of ref struct, read this article: Managed pointers, Span, ref struct, C#11 ref fields and the scoped keyword.

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 *