Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 20 additions & 33 deletions docs/csharp/language-reference/tokens/interpolated.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,26 @@ title: "$ - string interpolation - C# reference"
description: String interpolation provides a more readable and convenient syntax to format string output than traditional string composite formatting.
ms.date: 04/15/2022
f1_keywords:
- "$_CSharpKeyword"
- "$"
- "$_CSharpKeyword"
- "$"
helpviewer_keywords:
- "$ special character [C#]"
- "string interpolation [C#]"
- "interpolated string [C#]"
- "$ special character [C#]"
- "string interpolation [C#]"
- "interpolated string [C#]"
author: pkulikov
---

# $ - string interpolation (C# reference)

The `$` special character identifies a string literal as an *interpolated string*. An interpolated string is a string literal that might contain *interpolation expressions*. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.
The `$` special character identifies a string literal as an _interpolated string_. An interpolated string is a string literal that might contain _interpolation expressions_. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.

String interpolation provides a more readable, convenient syntax to format strings. It's easier to read than [string composite formatting](../../../standard/base-types/composite-formatting.md). Compare the following example that uses both features to produce the same output:

:::code language="csharp" source="./snippets/string-interpolation.cs" id="Snippet1":::

## Structure of an interpolated string

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.
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. To concantenate multiple interpolated strings, add the `$` special character to each string literal.

The structure of an item with an interpolation expression is as follows:

Expand All @@ -31,17 +32,17 @@ The structure of an item with an interpolation expression is as follows:

Elements in square brackets are optional. The following table describes each element:

|Element|Description|
|-------------|-----------------|
|`interpolationExpression`|The expression that produces a result to be formatted. String representation of `null` is <xref:System.String.Empty?displayProperty=nameWithType>.|
|`alignment`|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, it's left-aligned. For more information, see [Alignment Component](../../../standard/base-types/composite-formatting.md#alignment-component).|
|`formatString`|A format string that is supported by the type of the expression result. For more information, see [Format String Component](../../../standard/base-types/composite-formatting.md#format-string-component).|
| Element | Description |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `interpolationExpression` | The expression that produces a result to be formatted. String representation of `null` is <xref:System.String.Empty?displayProperty=nameWithType>. |
| `alignment` | 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, it's left-aligned. For more information, see [Alignment Component](../../../standard/base-types/composite-formatting.md#alignment-component). |
| `formatString` | A format string that is supported by the type of the expression result. For more information, see [Format String Component](../../../standard/base-types/composite-formatting.md#format-string-component). |

The following example uses optional formatting components described above:

:::code language="csharp" source="./snippets/string-interpolation.cs" id="Snippet2":::

Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every *interpolation expression* must be a string, and it must be a compile time constant.
Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every _interpolation expression_ must be a string, and it must be a compile time constant.

Beginning with C# 11, the interpolated expressions can include newlines. The text between the `{` and `}` must be valid C#, therefore it can include newlines that improve readability. The following example shows how newlines can improve the readability of an expression involving pattern matching:

Expand All @@ -55,9 +56,9 @@ You can use multiple `$` characters in an interpolated raw string literal to emb

:::code language="csharp" source="./snippets/string-interpolation.cs" id="RawInterpolatedLiteralStringWithBraces":::

If your output string should contain repeated `{` or `}` characters, you can add more `$` to designate the interpolated string. Any sequence of `{` or `}` shorter than the number or `$` will be embedded in the output string. As shown in the preceding example, sequences longer than the sequence of `$` characters embed the additional `{` or `}` characters in the output. The compiler issues an error if the sequence of brace characters is equal to or greater than double the length of the sequence of `$` characters.
If your output string should contain repeated `{` or `}` characters, you can add more `$` to designate the interpolated string. Any sequence of `{` or `}` shorter than the number of `$` will be embedded in the output string. As shown in the preceding example, sequences longer than the sequence of `$` characters embed the additional `{` or `}` characters in the output. The compiler issues an error if the sequence of brace characters is equal to or greater than double the length of the sequence of `$` characters.

You can try these features using the .NET 7 SDK. Or, if you have the .NET SDK 6.00.200 or later, you can set the `<LangVersion>` element in your *csproj* file to `preview`.
You can try these features using the .NET 7 SDK. Or, if you have the .NET SDK 6.00.200 or later, you can set the `<LangVersion>` element in your _csproj_ file to `preview`.

## Special characters

Expand All @@ -82,9 +83,9 @@ There are three implicit conversions from an interpolated string:

1. Conversion of an interpolated string to a <xref:System.FormattableString> instance that represents a composite format string along with the expression results to be formatted. That allows you to create multiple result strings with culture-specific content from a single <xref:System.FormattableString> instance. To do that, call one of the following methods:

- A <xref:System.FormattableString.ToString> overload that produces a result string for the <xref:System.Globalization.CultureInfo.CurrentCulture>.
- An <xref:System.FormattableString.Invariant%2A> method that produces a result string for the <xref:System.Globalization.CultureInfo.InvariantCulture>.
- A <xref:System.FormattableString.ToString(System.IFormatProvider)> method that produces a result string for a specified culture.
- A <xref:System.FormattableString.ToString> overload that produces a result string for the <xref:System.Globalization.CultureInfo.CurrentCulture>.
- An <xref:System.FormattableString.Invariant%2A> method that produces a result string for the <xref:System.Globalization.CultureInfo.InvariantCulture>.
- A <xref:System.FormattableString.ToString(System.IFormatProvider)> method that produces a result string for a specified culture.

The <xref:System.FormattableString.ToString(System.IFormatProvider)> provides a user-defined implementation of the <xref:System.IFormatProvider> interface that supports custom formatting. For more information, see the [Custom formatting with ICustomFormatter](../../../standard/base-types/formatting-types.md#custom-formatting-with-icustomformatter) section of the [Formatting types in .NET](../../../standard/base-types/formatting-types.md) article.

Expand All @@ -94,20 +95,6 @@ The following example uses implicit conversion to <xref:System.FormattableString

:::code language="csharp" source="./snippets/string-interpolation.cs" id="Snippet4":::

## Combining multiple interpolated strings

To combine multiple interpolated strings, use the interpolation expression for each:

```csharp
var firstWord = "Hello";
var secondWord = "World";

var combinedInterpolatedString = $"{firstWord}, " + $"{secondWord}!";

Console.WriteLine(combinedInterpolatedString)
// output: "Hello, World!"
```

## Other resources

If you're new to string interpolation, see the [String interpolation in C#](../../tutorials/exploration/interpolated-strings.yml) interactive tutorial. You can also check another [String interpolation in C#](../../tutorials/string-interpolation.md) tutorial. That tutorial demonstrates how to use interpolated strings to produce formatted strings.
Expand All @@ -118,7 +105,7 @@ If an interpolated string has the type `string`, it's typically transformed into

If an interpolated string has the type <xref:System.IFormattable> or <xref:System.FormattableString>, the compiler generates a call to the <xref:System.Runtime.CompilerServices.FormattableStringFactory.Create%2A?displayProperty=nameWithType> method.

Beginning with C# 10, when an interpolated string is used, the compiler checks if the interpolated string is assigned to a type that satisfies the *interpolated string handler pattern*. An *interpolated string handler* is a custom type that converts the interpolated string into a string. An interpolated string handler is an advanced scenario, typically used for performance reasons. You can learn about the requirements to build an interpolated string handler in the language specification for [interpolated string improvements](~/_csharplang/proposals/csharp-10.0/improved-interpolated-strings.md#the-handler-pattern). You can build one following the [interpolated string handler tutorial](../../whats-new/tutorials/interpolated-string-handler.md) in the What's new in C# section. In .NET 6, when you use an interpolated string for an argument of type `string`, the interpolated string is processed by the <xref:System.Runtime.CompilerServices.DefaultInterpolatedStringHandler?displayProperty=fullName>.
Beginning with C# 10, when an interpolated string is used, the compiler checks if the interpolated string is assigned to a type that satisfies the _interpolated string handler pattern_. An _interpolated string handler_ is a custom type that converts the interpolated string into a string. An interpolated string handler is an advanced scenario, typically used for performance reasons. You can learn about the requirements to build an interpolated string handler in the language specification for [interpolated string improvements](~/_csharplang/proposals/csharp-10.0/improved-interpolated-strings.md#the-handler-pattern). You can build one following the [interpolated string handler tutorial](../../whats-new/tutorials/interpolated-string-handler.md) in the What's new in C# section. In .NET 6, when you use an interpolated string for an argument of type `string`, the interpolated string is processed by the <xref:System.Runtime.CompilerServices.DefaultInterpolatedStringHandler?displayProperty=fullName>.

> [!NOTE]
> One side effect of interpolated string handlers is that a custom handler, including <xref:System.Runtime.CompilerServices.DefaultInterpolatedStringHandler?displayProperty=nameWithType>, may not evaluate all the expressions used as placeholders in the interpolated string under all conditions. That means side-effects in those expressions may not occur.
Expand Down