This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
$
The$
character identifies a string literal as aninterpolated string. An interpolated string is a string literal that might containinterpolation expressions. When an interpolated string is resolved to a result string, the compiler replaces items with interpolation expressions by the string representations of the expression results.
String interpolation provides a more readable, convenient syntax to format strings. It's easier to read thanstring composite formatting. The following example uses both features to produce the same output:
var name = "Mark";var date = DateTime.Now;// Composite formatting:Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);// String interpolation:Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");// Both calls produce the same output that is similar to:// Hello, Mark! Today is Wednesday, it's 19:40 now.
You can use an interpolated string to initialize aconstant string. You can do that only if all interpolation expressions within the interpolated string are constant strings as well.
To identify a string literal as an interpolated string, prepend it with the$
symbol. You can't have any white space between the$
and the"
that starts a string literal.
The structure of an item with an interpolation expression is as follows:
{<interpolationExpression>[,<width>][:<formatString>]}
Elements in square brackets are optional. The following table describes each element:
Element | Description |
---|---|
interpolationExpression | The expression that produces a result to be formatted. When the expression isnull , the output is the empty string (String.Empty). |
width | The constant expression whose value defines the minimum number of characters in the string representation of the expression result. If positive, the string representation is right-aligned; if negative, left-aligned. For more information, see theWidth component section of theComposite formatting article. |
formatString | A format string supported by the type of the expression result. For more information, see theFormat string component section of theComposite formatting article. |
The following example uses optional formatting components described in the preceding table:
Console.WriteLine($"|{"Left",-7}|{"Right",7}|");const int FieldWidthRightAligned = 20;Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");// Output is:// |Left | Right|// 3.14159265358979 - default formatting of the pi number// 3.142 - display only three decimal digits of the pi number
Beginning with C# 11, you can use new-lines within an interpolation expression to make the expression's code more readable. The following example shows how new-lines can improve the readability of an expression involvingpattern matching:
string message = $"The usage policy for {safetyScore} is { safetyScore switch { > 90 => "Unlimited usage", > 80 => "General usage, with daily safety check", > 70 => "Issues must be addressed within 1 week", > 50 => "Issues must be addressed within 1 day", _ => "Issues must be addressed before continued use", } }";
Beginning with C# 11, you can use an interpolatedraw string literal, as the following example shows:
int X = 2;int Y = 3;var pointMessage = $"""The point "{X}, {Y}" is {Math.Sqrt(X * X + Y * Y):F3} from the origin""";Console.WriteLine(pointMessage);// Output is:// The point "2, 3" is 3.606 from the origin
To embed{
and}
characters in the result string, start an interpolated raw string literal with multiple$
characters. When you do that, any sequence of{
or}
characters shorter than the number of$
characters is embedded in the result string. To enclose any interpolation expression within that string, you need to use the same number of braces as the number of$
characters, as the following example shows:
int X = 2;int Y = 3;var pointMessage = $$"""{The point {{{X}}, {{Y}}} is {{Math.Sqrt(X * X + Y * Y):F3}} from the origin}""";Console.WriteLine(pointMessage);// Output is:// {The point {2, 3} is 3.606 from the origin}
In the preceding example, an interpolated raw string literal starts with two$
characters. You need to put every interpolation expression between double braces ({{
and}}
). A single brace is embedded into a result string. If you need to embed repeated{
or}
characters into a result string, use an appropriately greater number of$
characters to designate an interpolated raw string literal. If the string literal has more repeated braces than the number of$
characters, the{
and}
characters are grouped from inside to outside. In the preceding example, the literalThe point {{{X}}, {{Y}}}
interprets{{X}}
and{{Y}}
as interpolated expressions. The outer{
and}
are included verbatim in the output string.
To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}". For more information, see theEscaping braces section of theComposite formatting article.
As the colon (":") has special meaning in an interpolation expression item, to use aconditional operator in an interpolation expression. Enclose that expression in parentheses.
The following example shows how to include a brace in a result string. It also shows how to use a conditional operator:
string name = "Horace";int age = 34;Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");// Output is:// He asked, "Is your name Horace?", but didn't wait for a reply :-{// Horace is 34 years old.
An interpolatedverbatim string starts with both the$
and@
characters. You can use$
and@
in any order: both$@"..."
and@$"..."
are valid interpolated verbatim strings. For more information about verbatim strings, see thestring andverbatim identifier articles.
By default, an interpolated string uses the current culture defined by theCultureInfo.CurrentCulture property for all formatting operations.
To resolve an interpolated string to a culture-specific result string, use theString.Create(IFormatProvider, DefaultInterpolatedStringHandler) method, which is available beginning with .NET 6. The following example shows how to do that:
double speedOfLight = 299792.458;System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");string messageInCurrentCulture = $"The speed of light is {speedOfLight:N3} km/s.";var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");string messageInSpecificCulture = string.Create( specificCulture, $"The speed of light is {speedOfLight:N3} km/s.");string messageInInvariantCulture = string.Create( System.Globalization.CultureInfo.InvariantCulture, $"The speed of light is {speedOfLight:N3} km/s.");Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");// Output is:// nl-NL The speed of light is 299.792,458 km/s.// en-IN The speed of light is 2,99,792.458 km/s.// Invariant The speed of light is 299,792.458 km/s.
In .NET 5 and earlier versions of .NET, use implicit conversion of an interpolated string to aFormattableString instance. Then, you can use an instanceFormattableString.ToString(IFormatProvider) method or a staticFormattableString.Invariant method to produce a culture-specific result string. The following example shows how to do that:
double speedOfLight = 299792.458;FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");string messageInSpecificCulture = message.ToString(specificCulture);Console.WriteLine(messageInSpecificCulture);// Output:// The speed of light is 2,99,792.458 km/s.string messageInInvariantCulture = FormattableString.Invariant(message);Console.WriteLine(messageInInvariantCulture);// Output is:// The speed of light is 299,792.458 km/s.
For more information about custom formatting, see theCustom formatting with ICustomFormatter section of theFormatting types in .NET article.
If you're new to string interpolation, see theString interpolation in C# interactive tutorial. That tutorial demonstrates how to use interpolated strings to produce formatted strings.
The compiler checks if an interpolated string is assigned to a type that satisfies theinterpolated string handler pattern. Aninterpolated string handler is a type that converts the interpolated string into a result string. When an interpolated string has the typestring
, it's processed by theSystem.Runtime.CompilerServices.DefaultInterpolatedStringHandler. For the example of a custom interpolated string handler, see theWrite a custom string interpolation handler tutorial. Use of an interpolated string handler is an advanced scenario, typically required for performance reasons.
Note
One side effect of interpolated string handlers is that a custom handler, includingSystem.Runtime.CompilerServices.DefaultInterpolatedStringHandler, might not evaluate all the interpolation expressions within the interpolated string under all conditions. That means side effects of those expressions might not occur.
If an interpolated string has the typestring
, it's typically transformed into aString.Format method call. The compiler can replaceString.Format withString.Concat if the analyzed behavior would be equivalent to concatenation.
If an interpolated string has the typeIFormattable orFormattableString, the compiler generates a call to theFormattableStringFactory.Create method.
For more information, see theInterpolated string expressions section of theC# language specification and the following new feature specifications:
Was this page helpful?
Was this page helpful?