String interpolation and formatting
Build strings from values with $"...", then bend the output with format specifiers, alignment, and raw literals.
An interpolated string drops expressions straight into text; a :format suffix controls how each value renders (N2, C, P, X), an ,width aligns it, and """ raw literals let you write braces and quotes without escaping.
Interpolation basics
Prefix a string literal with $ to make it interpolated: any {expression} inside is evaluated and its ToString() spliced into the result. The expression can be a variable, a property, a method call, or arithmetic β $"{a} + {b} = {a + b}". To print a literal brace, double it: {{ becomes { and }} becomes }.
Interpolation is the modern replacement for String.Format("{0} {1}", a, b), where you had to match numbered placeholders to arguments by position. The interpolated form reads in source order, so there is nothing to mis-count.
Format and alignment specifiers
Inside a placeholder you can append two optional clauses after the expression: {value,alignment:format}.
- The format clause (after
:) is a standard or custom format string. Common standard ones:N2(number, 2 decimals, group separators),C(currency),P(percent, scales by 100),F3(fixed-point, 3 decimals),X(uppercase hex),D5(integer padded to 5 digits). Custom patterns like0.0oryyyy-MM-ddwork too. - The alignment clause (after
,) is a minimum field width: positive right-aligns, negative left-aligns, padding with spaces.{name,-10}left-aligns in a 10-wide column.
Both are optional and order matters β alignment comes first, then the colon-format: {total,12:N2}.
Raw string literals
A raw string literal is delimited by three or more double-quotes ("""). Inside, backslashes and quotes are literal β no escaping β which makes JSON, regex, and file paths far cleaner. When the opening """ is on its own line, the closing """ sets the indentation: whitespace to the left of the closing delimiter is stripped from every line, so you can indent the literal to match your code.
Raw literals also interpolate: prefix with $ and use a single { }. If your content itself contains braces, add more dollar signs β $$"""...""" makes {{ the interpolation delimiter so single braces stay literal.
Try it 5 examples
Embed expressions with $\
C#introEach {...} is evaluated in place β including the arithmetic {copies * price} which yields 13.5 β while the doubled {{braces}} print as a single literal {braces}, showing how interpolation reads in source order with no positional placeholders to mis-count.