Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 182 ยท Strings

Interpolation and Formatting

Master C# string interpolation and formatting - alignment, format specifiers, IFormatProvider and culture, custom ToString and IFormattable, string.Format and interpolated string handlers.

Turning values into readable text is one of the most common jobs in any program: a price with two decimals, a date in the user's format, a table whose columns line up. C# offers one friendly syntax for it, string interpolation ($"..."), and a whole system underneath that decides how each value is converted: format strings, format providers and the IFormattable interface.

You saw the basics in Console Output and Formatting. Here we go deeper: how alignment and specifiers combine, why culture matters, how to make your own types format themselves, and what the compiler really generates for an interpolated string.

Interpolation in one minute

A string that starts with $ may contain holes in curly braces. Each hole contains any C# expression, and its value is converted to text. The general shape of a hole is {expression,alignment:formatString}; both parts after the expression are optional.

C# Holes can contain expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the parentheses around the conditional operator: a bare : inside a hole would start the format string, so any expression that uses ?: must be parenthesized. To print a literal brace, double it.

Since C# 11 a hole may span several lines, which helps when an expression is long. And since C# 6 nothing about this costs runtime speed compared to hand-written concatenation: the compiler generates efficient code (more on that below).

Alignment and format strings

The number after the comma is the alignment, the minimum width of the field. A positive value right-aligns, a negative one left-aligns. The text after the colon is the format string, which depends on the type of the value.

C# A small table with alignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Alignment pads with spaces and never truncates: a value wider than the field simply takes more room. The pattern {value,10:F2} reads "right-align in 10 columns, formatted with two decimals".

Standard numeric format specifiers

Specifier Meaning Example (value 1234.5678)
F2 Fixed-point, 2 decimals 1234.57
N2 Number with group separators 1,234.57
C Currency ยค1,234.57 in the invariant culture
P1 Percent (value is multiplied by 100) 123,456.8 %
E3 Scientific 1.235E+003
D6 Integer digits, zero padded (integers only) needs an int
X, X4 Hexadecimal (integers only) FF, 00FF
G General (default) 1234.5678
C# Standard format specifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The ยค symbol you see for currency appears because the sandbox uses the invariant culture, which has no real currency symbol. On a machine set to the United States it would print $. Note also the rounding line. The values 2.5, 3.5 and 0.125 are exact ties in binary, and on this runtime F0 and F2 print 2, 4 and 0.12, so ties went to the even neighbour, the same as Math.Round. Do not build money logic on how a format string happens to round: round first with Math.Round(value, 2, MidpointRounding.AwayFromZero) (or whichever rule your business needs) and then format the result.

Custom numeric and date formats

When the standard specifiers do not fit, build a pattern from placeholders: 0 is a mandatory digit, # an optional digit, . the decimal point and , the group separator. Dates have their own letters (yyyy, MM, dd, HH, mm, ss).

C# Custom patterns for numbers and dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Single letters like t, D and O are standard date formats; O (round-trip) is the right choice for storing and exchanging timestamps because it is culture-independent. See Dates and Times for the full story.

Culture: the same value, different text

In many countries 1234.5 is written 1.234,5. Which style appears depends on the format provider, an IFormatProvider such as a CultureInfo. If you do not pass one, .NET uses the current culture of the thread, which comes from the user's operating system. For text shown to a user that is exactly right. For text a program will read again (files, URLs, logs, JSON) it is a classic bug source: your German colleague's machine writes 3,14 and your parser expecting 3.14 fails.

C# Choosing the culture explicitly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Our server runs in invariant-globalization mode, so named cultures such as de-DE throw CultureNotFoundException. On your own computer the last call prints 1.234.567,89 (shown here read-only):

TEXT
price.ToString("N2", CultureInfo.GetCultureInfo("de-DE"))   ->  1.234.567,89
price.ToString("N2", CultureInfo.GetCultureInfo("fr-FR"))   ->  1 234 567,89   (narrow no-break space)
price.ToString("C",  CultureInfo.GetCultureInfo("en-US"))   ->  $1,234,567.89

The rule of thumb: user interface text uses the user's culture; machine-readable text uses CultureInfo.InvariantCulture. string.Create(provider, $"...") applies a provider to all holes of an interpolated string at once.

string.Format and composite formatting

Before interpolation there was composite formatting: a template with numbered placeholders , and a list of arguments. It still matters, because the template can live outside your code (a resource file, a database) and be filled in later, and because Console.WriteLine("{0}", x) and string.Format are everywhere in older code.

C# string.Format and composite formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Compared with interpolation, composite formatting has a weakness: nothing links the numbers to the arguments at compile time, so a mismatch is only found at run time (a FormatException). Prefer interpolation in code and use composite templates when the text must be external. Analyzers can check the placeholder count for constant templates.

Making your own types formattable

Every object has a ToString() method, which interpolation calls when a hole contains it. The default implementation prints the type name, which is rarely helpful. Override it for a readable form.

To support format strings for your type ({temp:F}, {money:long}) implement IFormattable, whose single method is ToString(string? format, IFormatProvider? provider).

C# A type with its own format strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three details are worth copying into your own code: treat null or empty format as a sensible default, pass the provider along to the number formatting you delegate to, and throw FormatException for unknown formats instead of guessing. Records already generate a ToString, so we override it explicitly here.

If you also want a type to be parsed back from text, implement IParsable<T> or ISpanParsable<T> (C# 11, .NET 7); that is covered in Generic Math.

What the compiler really does: interpolated string handlers

An interpolated string is not always turned into string.Format. Since C# 10 / .NET 6 the compiler lowers $"..." to calls on an interpolated string handler: a struct that receives the literal pieces through AppendLiteral and each hole through AppendFormatted. The default handler (DefaultInterpolatedStringHandler) appends directly into a pooled buffer, so most interpolations allocate only the final string and don't box value types.

The feature is open to your own types. A method that takes an [InterpolatedStringHandlerArgument] handler parameter can decide not to evaluate the holes at all. The classic use is logging: when the level is disabled, no formatting work happens. Here is a miniature version you can run.

C# A custom interpolated string handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When the constructor sets shouldAppend to false, the compiler skips all later AppendLiteral and AppendFormatted calls, including evaluating the hole expressions. That is why Expensive() never runs while logging is disabled. The same mechanism powers ILogger source generators, Debug.Assert messages and ArgumentNullException.ThrowIfNull-style helpers. You will rarely write a handler yourself, but knowing it exists explains why interpolation is the preferred formatting tool in modern C#.

Raw interpolation and constants

Interpolated strings can be const when every hole is itself a constant string (C# 10), and they can combine with verbatim @ and raw """ strings. Those are covered in Raw, Verbatim and UTF-8 String Literals.

Common mistakes

  • Using the current culture for machine-readable text. Use CultureInfo.InvariantCulture.
  • Forgetting parentheses around ?: inside a hole.
  • Expecting alignment to truncate. It only pads.
  • Building SQL or shell commands with interpolation: the values are pasted into the text. Use parameters (see ADO.NET Concepts).
  • Formatting a decimal money value with double arithmetic and then wondering about cents.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In $"{name,-10}|", what does -10 mean?

    The number after the comma is the minimum field width. A negative number left-aligns the text; a positive number right-aligns it.
  2. 2. Which line correctly puts a conditional expression into an interpolation hole?

    A colon inside a hole starts the format string, so the conditional expression must be wrapped in parentheses.
  3. 3. Which culture should you use to write a number into a file that other programs will parse?

    The invariant culture produces the same text on every machine, so the file can be parsed back reliably.
  4. 4. Which interface lets your own type react to format strings like {value:F2}?

    IFormattable.ToString(string? format, IFormatProvider? provider) receives the text after the colon and the provider.
  5. 5. Why can a custom interpolated string handler make logging cheaper?

    The handler constructor can report shouldAppend = false. The compiler then does not call AppendFormatted, so the hole expressions are not even evaluated.

Summary

  • $"..." holes have the shape {expression,alignment:format}; negative alignment left-aligns, and ?: needs parentheses.
  • Standard specifiers (F, N, C, P, E, D, X) and custom patterns (0.00, #,##0, yyyy-MM-dd) shape numbers and dates.
  • The format provider decides culture rules: current culture for people, InvariantCulture for machines.
  • string.Format uses numbered placeholders and suits external templates; interpolation is safer in code.
  • Implement IFormattable to give your own types format strings.
  • The compiler lowers interpolation to interpolated string handlers, which avoid allocations and enable lazy formatting.

Next: StringBuilder