String interpolation and formatting

An interpolated string

A string that starts with $ may hold an expression in braces, and the expression is evaluated where the string is written. The result is a single string, built by the compiler, and it costs no more than the concatenation it replaces.

string name = "Ada"; int year = 1843; Console.WriteLine($"{name} wrote notes in {year}."); Console.WriteLine($"{name.ToUpper()} is {name.Length} letters."); Console.WriteLine($"next year: {year + 1}");

dotnet run

Ada wrote notes in 1843.
ADA is 3 letters.
next year: 1844

Any expression works in the braces: a member access, a method call, a calculation. A quote inside a hole is allowed in C# 11 and later, so $"{flag ? "yes" : "no"}" is one string with two literals in it.

Alignment and format specifiers

After the expression a hole may hold two more parts, separated by commas and colons: an alignment and a format. A positive alignment pads on the left, a negative one pads on the right, and the format is what ToString of that type understands.

string name = "Ada"; decimal price = 19.9m; Console.WriteLine($"|{name,-6}|{name,6}|"); Console.WriteLine($"{price:F2}"); Console.WriteLine($"{42:D5}"); Console.WriteLine($"{1234567:N0}"); Console.WriteLine($"{0.256:P1}"); Console.WriteLine($"{DateTime.UnixEpoch:yyyy-MM-dd}");

dotnet run

|Ada | Ada|
19.90
00042
1,234,567
25.6 %
1970-01-01

Five formats, five habits:

The percent sign came out as 25.6 % with a space, because the culture of this container puts one there. The part on culture and formatting explains why, and how to ask for the invariant culture instead.

string.Format and braces

An interpolated string is the readable form of string.Format, and the older form still appears in code and in format strings read from a file:

Console.WriteLine(string.Format("{0} + {1} = {2}", 1, 2, 3)); Console.WriteLine($"{{a literal brace}}"); Console.WriteLine($"{Math.PI:F4}"); Console.WriteLine($"sum: {(1 + 2) * 3}");

dotnet run

1 + 2 = 3
{a literal brace}
3.1416
sum: 9

{{ and }} are the escapes for a brace, because a single brace starts a hole. A format string that a program builds at run time cannot use the interpolated form at all: the pieces are not known when the source is compiled, and string.Format is what is left.

A null inside the braces

A hole with a null in it prints nothing: the interpolated string does not throw, and the null becomes an empty piece.

string? missing = null; Console.WriteLine($"name: {missing ?? "none"}"); Console.WriteLine($"length: {missing?.Length}"); Console.WriteLine($"epoch: {DateTime.UnixEpoch:O}");

dotnet run

name: none
length:
epoch: 1970-01-01T00:00:00.0000000Z

The second line ends after the space, because missing?.Length is a int? that holds no value. A reader cannot see the difference between an empty value and a missing one, which is why the first line uses ?? to say none in words.

O is the round-trip format of a date: it keeps every part of the value, including the kind and the fraction of a second, so the text can be parsed back into the same instant.

Exercises

  1. Print a table of three prices with F2 and an alignment of ten characters. Which side does a positive alignment pad?
  2. Replace string.Format with an interpolated string and check that the output is identical.
  3. Print 1234.5678 with F2, F4 and N2. Which digits are lost?
  4. Put a quote inside a hole, as in the paragraph above, and check the build. Which C# version does it need?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the $ in front of a string literal do?

    Answer

    It makes the braces holes that hold expressions

    The $ prefix turns the literal into an interpolated string, and each hole is evaluated when the string is built.

  2. What does the alignment -6 in {name,-6} do?

    Answer

    Pads the value on the right to six characters

    A negative alignment is left-justified, so the padding goes after the text; a positive one pads in front.

  3. What does this program print? decimal price = 4.5m; Console.WriteLine($"{price:F2}");

    Answer

    4.50

    F2 is fixed-point with two decimals, and decimal has a ToString that understands it.

  4. What does this program print? Console.WriteLine($"{42:D5}");

    Answer

    00042

    D is the decimal format of an integer and its number is the minimum count of digits, which pads with zeros.

  5. What does this program print? Console.WriteLine($"{{x}}");

    Answer

    {x}

    A doubled brace is a literal brace, so the string holds the three characters of {x}.

  6. What does this program print? string? missing = null; Console.WriteLine($"[{missing}]");

    Answer

    []

    A null in a hole becomes an empty piece of text rather than the word null, and nothing is thrown.

  7. Which format groups the thousands of a number?

    Answer

    N0

    N is the number format with group separators; D pads digits, F fixes decimals and P adds a percent sign.

  8. What does this program print? int a = 2; int b = 3; Console.WriteLine($"{a} * {b} = {a * b}");

    Answer

    2 * 3 = 6

    The holes hold the values and the product, so the line reads as an arithmetic sentence.

  9. How does a program format a pattern that only exists at run time?

    Answer

    With string.Format, because an interpolated string is fixed at compile time

    The holes of an interpolated string are part of the source; a pattern in a variable is passed to string.Format as a format string.

  10. What does this program print? Console.WriteLine($"{0.256:P1}");

    Answer

    25.6 %

    P multiplies by a hundred, keeps one decimal and adds the percent sign; this culture puts a space before it.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev