C#

All the Ways to Do String Interpolation in C#

Duende Software Blog Khalid Abuhakmeh
C#

Khalid Abuhakmeh walks through C# string interpolation from plain $"" literals to format specifiers, alignment, raw string literals and interpolated string handlers, then flags the two places where reaching for it by habit causes real trouble: structured logging and SQL.

Key points

  • A colon applies a format specifier: {price:C}, {now:yyyy-MM-dd} and {255:X4} follow string.Format rules.
  • A comma plus a width pads the value; negative left-aligns, and the format specifier comes after alignment.
  • In a $$ raw string literal, JSON braces stay literal while {{user}} is the interpolation hole.
  • FormattableString.Invariant(...) keeps machine-readable output identical on every machine, whatever the server culture.
  • Interpolated string handlers (.NET 6 / C# 10) pass literal parts and values separately, so Debug.Assert and StringBuilder skip the allocation.
  • Give ILogger named placeholders and separate arguments; interpolating the template drops the queryable fields.

Why it matters

This is a reminder piece: none of it is new, yet the failure modes it describes keep reaching production. Teams that moved to source-generated logging or Serilog templates usually got the logging half right; the SQL half still bites in code written before EF Core's parameterized APIs were in common use.

Treat it as a checklist against your own codebase rather than a tutorial. Grep for interpolated strings handed to logger methods and for concatenated SQL, and make sure any string passed to another system as a template — cache keys, message bodies, file names — is built with invariant culture. Whether interpolated string handlers help your hot paths depends on the API you call, not on the syntax.

Real-world use

  • Structured logging where each value must stay a searchable field.
  • EF Core FromSqlInterpolated queries that turn user input into real parameters.
  • Generating JSON or code snippets where literal braces must survive interpolation.
  • Console output that needs aligned columns without a table library.

This summary was generated by the agent from the original post on Duende Software Blog. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message