Skip to content

Enum format strings are ignored on .NET 8 or later #34

Open

Description

@aetos382

Summary

On .NET 8 or later, Utf8StringWriter ignores the format string of enum values and always writes the name, so {x:D} writes Friday instead of 5. DefaultInterpolatedStringHandler, which C# uses for interpolated strings converted to string, writes the underlying value, as x.ToString("D") does.

We found this in ZLogger: the UTF-8 output of [ZLoggerMessage] methods writes {x:D} as the name, while their message string writes the value. ZLogger works around it for ZLog in Cysharp/ZLogger#260.

Environment

Utf8StringInterpolation 1.3.2 (the net8.0 build), .NET SDK 11.0.100, Windows 11.

Repro

#:package Utf8StringInterpolation@1.3.2

using System;
using System.Text;
using Utf8StringInterpolation;

var e = DayOfWeek.Friday;
Show($"{e:D}", Utf8String.Format($"{e:D}"));
Show($"{e:X}", Utf8String.Format($"{e:X}"));
Show($"[{e,6:D}]", Utf8String.Format($"[{e,6:D}]"));

static void Show(string expected, byte[] actual)
    => Console.WriteLine($"expected: {expected}, actual: {Encoding.UTF8.GetString(actual)}");

Run with dotnet run repro.cs.

Actual

expected: 5, actual: Friday
expected: 00000005, actual: Friday
expected: [     5], actual: [Friday]

Cause

AppendFormattedCore passes enum values to AppendEnum, which receives the format but writes the value through an interpolated string whose hole has no format:

while (!Utf8.TryWrite(dest, formatProvider, $"{value}", out written))

The typeof(T).IsEnum branch exists only in the .NET 8 build.

Possible fix

Build the Utf8.TryWriteInterpolatedStringHandler by hand, so that the format can be passed to it:

var handler = new Utf8.TryWriteInterpolatedStringHandler(0, 1, dest, formatProvider, out _);
handler.AppendFormatted(value, format);
if (Utf8.TryWrite(dest, formatProvider, ref handler, out written)) { /* done */ }

I checked that this compiles for an unconstrained T and writes Friday, 5, 00000005, and 10 for Friday with no format, D, and X, and for (DayOfWeek)10 with no format. The handler has to be created again for each attempt when dest grows.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions