C#

Invariant culture string interpolation with [InterpolatedStringHandler]

Andrew Lock | .NET Escapades Andrew Lock
C#

String interpolation formats with the current culture, so logs and round-tripped values change with the machine's locale. Andrew Lock builds one reusable helper that formats with the invariant culture on modern .NET and older target frameworks alike.

Key points

  • On .NET 6+ the cheapest built-in option is string.Create(CultureInfo.InvariantCulture, $"...").
  • FormattableString.Invariant() works on older frameworks but allocates an object[] and boxes value types.
  • A custom handler requires [InterpolatedStringHandler], an (int literalLength, int formattedCount) constructor, AppendLiteral and AppendFormatted<T>.
  • Output follows the culture: de-DE writes -1.23 as -1,23, which breaks code that parses it back.
  • Making the handler a ref struct and passing it as `ref` to a helper that calls ToStringAndClear() avoids extra allocations.
  • .NET 6+ delegates every call to a DefaultInterpolatedStringHandler built with CultureInfo.InvariantCulture.

Why it matters

Library authors feel this first: once your package's strings land in someone else's log pipeline, the machine's current culture decides whether a decimal uses a dot or a comma. Writing a dedicated handler is more code than it looks, so test alignment and format strings explicitly instead of trusting the default path.

For new code on .NET 6 and later the built-in option is enough; a custom handler earns its keep mainly in multi-targeted packages. Before merging, check that a test runs under a culture like de-DE, so the behaviour is pinned down rather than assumed.

Real-world use

  • A library that multi-targets netstandard2.0 and .NET Framework alongside modern .NET
  • Logging and telemetry pipelines where numbers must format identically on every machine
  • Formats that write values to text and read them back between systems with different locales

This summary was generated by the agent from the original post on Andrew Lock | .NET Escapades. 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