skip to content

In a C# interpolated string such as $"{amount,10:N2}", what do the 10 and the N2 do, and what if the value is wider?

level: juniorimportance: must knowfreq 62%

answer

  1. three parts inside the braces
  2. comma part versus colon part
  3. sign decides which side pads
  4. a minimum, not a maximum

basics

~20 s

In a hole {expr,width:format}, the comma number is a minimum width (positive right-aligns, negative left-aligns) and the colon text is the value's format string, here two-decimal N2. A wider value is printed in full, never truncated.

solid answer

~40 s

A hole has the shape `{expression,width:format}`. The width is a constant that sets the *minimum* field size: positive pads with spaces on the left (right-aligned), negative pads on the right (left-aligned). The format string goes to the value's formatter, so `N2` on a decimal means group separators and two rounded decimals, and `yyyy-MM-dd` on a `DateTime` is a date pattern. A value longer than the width is printed whole and pushes the column out; nothing is cut. `string.Format` uses the same syntax with an index, `{1,10:N2}`, but a bad index there only fails at run time with `FormatException`. Two small rules: double a literal brace (`{{`), and wrap a conditional expression in parentheses or the compiler reports CS8361.

code

csharp · 21 lines
csharp
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

var lines = new (string Item, decimal Amount, DateTime Due)[]
{
    ("Hosting", 1234.5m, new DateTime(2026, 11, 1)),
    ("Support plan", 89m, new DateTime(2026, 11, 15)),
};

foreach (var (item, amount, due) in lines)
    Console.WriteLine($"|{item,-14}|{amount,10:N2}|{due:yyyy-MM-dd}|");

// The same holes in composite formatting: {index,width:format}
Console.WriteLine(string.Format("|{0,-14}|{1,10:N2}|{2:yyyy-MM-dd}|", "Licence", 12000m, new DateTime(2026, 12, 1)));

// Width is a minimum, never a cut-off
Console.WriteLine($"|{"Implementation services",-14}|{1234567.891m,10:N2}|");

// Literal braces are doubled
Console.WriteLine($"{{total}} = {1234.5m:N2}");

go deeper

for a junior

Recall the hole shape {expression,width:format}, which sign of the width right-aligns, and that N2 means two decimals with group separators.

for a middle

Explain that width is a minimum and never truncates, that the format string is interpreted by the value's type, and that string.Format shares the syntax but checks indexes only at run time.

for a senior

Show how a fixed-width report breaks on long values and on other cultures, and how you would guard both: measured widths or explicit truncation, and a provider passed on purpose.

for a principal

Weigh interpolation against composite format strings kept as data, for example templates loaded at run time, where you give up compile-time binding and must test format errors instead.

## The three parts of an interpolation hole An **interpolated string** is a string literal prefixed with `$`. Every `{ ... }` inside it is an **interpolation hole** (the docs describe it as an item with an interpolation expression), and a hole has up to three parts: ```text {<expression>[,<width>][:<formatString>]} ``` | Part | Example | What it does | |---|---|---| | expression | `amount` | Any C# expression; its value is what gets printed. A `null` value prints as an empty string. | | width (after the comma) | `10`, `-14` | A **constant** that sets the *minimum* number of characters. Positive right-aligns (pads on the left); negative left-aligns (pads on the right). | | format string (after the colon) | `N2`, `yyyy-MM-dd` | Text handed to the value's own formatter, for example `IFormattable.ToString(format, provider)`. | The width is also called **alignment**: that is the parameter name on the `AppendFormatted<T>(T value, int alignment, string? format)` overloads the compiler calls behind the scenes. ## Width pads, it never truncates The width is a floor, not a column limit: - `{amount,10:N2}` formats the amount first (`1,234.50`, eight characters) and then pads it with spaces on the left to ten characters. - `{item,-14}` pads the item name on the right, which is how a text column left-aligns. - A value **longer** than the width is printed in full. `{"Implementation services",-14}` prints all 23 characters and pushes the rest of the line to the right. No exception, no ellipsis. - Padding uses spaces only. Zero padding is a job for the format string (`D5` on an integer, or a custom pattern like `00000`), not for the width. So a fixed-width invoice printout needs either column widths that fit the longest value or an explicit cut of the text before it is formatted. ## Format strings: N2 and yyyy-MM-dd The format string is interpreted by the value's type, not by the language: - On a `decimal`, `double` or `int`, **`N2`** is the standard numeric "number" format: group separators plus exactly two decimal places, rounded. `1234567.891m` prints `1,234,567.89` under the invariant culture. - **`F2`** gives two decimals with no group separator; **`C`** adds a currency symbol; **`P0`** prints a percentage. - On a `DateTime`, **`yyyy-MM-dd`** is a custom date pattern. `MM` is the month and `mm` the minutes, a classic slip. - The separators and symbols come from the **current culture** unless you pass one, so `N2` is not "always a comma and a dot". A format string the type cannot use is not caught by the compiler; it is the formatter's job at run time. ## The same syntax in string.Format Interpolation is a friendlier spelling of **composite formatting**, the older API behind `string.Format`, `Console.WriteLine(string, ...)` and `StringBuilder.AppendFormat`. There the hole holds an argument **index** instead of an expression: ```csharp string.Format("|{0,-14}|{1,10:N2}|{2:yyyy-MM-dd}|", "Licence", 12000m, due); ``` The difference that matters in review is *when* a mistake surfaces: 1. In `$"..."` every hole is an expression the compiler binds, so a misspelt variable is a compile error. 2. In `string.Format`, the format string is just data. `string.Format("{0} due {2}", "Hosting", 1234.5m)` compiles and throws **`FormatException`** at run time because index 2 has no argument. Analyzer rule CA2241 can flag such calls; the compiler itself does not. ## Small traps worth naming - **Literal braces** are doubled in a regular interpolated or composite string: `$"{{total}} = {sum:N2}"` prints `{total} = ...`. A bare `}` is CS8086. - **The conditional operator** needs parentheses, because its `:` would start a format string: `$"{(overdue ? "OVERDUE" : "open")}"`. Without them the SDK reports CS8361, "A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation. Parenthesize the conditional expression." - **The width must be a constant.** To size a column at run time, build the padding yourself with `PadLeft` or `PadRight`. - **Culture applies to every hole.** Set it or pass it explicitly when the output must look the same on every machine.

  • Why does $"{overdue ? "OVERDUE" : "open"}" fail to compile, and what is the fix?
    Inside a hole the first top-level colon starts the format string, so the compiler reads `"OVERDUE" : "open"` as broken syntax and reports CS8361, asking you to parenthesize the conditional expression. Writing `{(overdue ? "OVERDUE" : "open")}` makes the colon part of the expression again.
  • What does string.Format("{0} due {2}", "Hosting", 1234.5m) do?
    It compiles, because a composite format string is just a string to the compiler, and throws `FormatException` at run time: index 2 is outside the two arguments. An interpolated string cannot have this mismatch, since each hole is an expression the compiler binds. Analyzer rule CA2241 can catch the composite case at build time.
  • How do you print a literal brace next to a formatted value?
    Double it. In a regular `$"..."` or a composite format string, `{{` prints `{` and `}}` prints `}`, so `$"{{total}} = {sum:N2}"` prints `{total} = 1,234.50` under the invariant culture. A single unmatched `}` is a compile error (CS8086) in an interpolated string.

A hole's width works like the minimum size of a box on a printed form: a short entry leaves blank space on one side, and a long entry is still written in full, running past the box instead of being clipped.

  • A width shorter than the value truncates the value to fit the column.
  • A positive width pads on the right, so the text comes out left-aligned.
  • N2 always prints a comma group separator and a dot decimal point.
  • A wrong placeholder index in string.Format is a compile error.
  • The width can be any int variable, so columns can be sized at run time inside the hole.