Roslyn: Interpolated String Parse-Error

Created on 20 Dec 2020  路  6Comments  路  Source: dotnet/roslyn

Version Used:
3.9.0-2.final

Steps to Reproduce:
The following code is parsed invalid:

using System;

namespace Tests
{
    class App
    {
        static void Main()
        {
            string s = $"InterpolatedString {{{27,7:X}}}";

            Console.WriteLine(s);
        }
    }
}

Easy visible with syntax highlighting:
grafik

Expected Behavior:
The curly braces do not belong to InterpolationFormatClauseSyntax. The content should be simply: "X".

Actual Behavior:
we get an InterpolationFormatClauseSyntax with the content "X}"

Area-Compilers untriaged

Most helpful comment

@bernd5 @PathogenDavid I didn't know about that, thanks for teaching me something new. I have opened https://github.com/dotnet/docs/issues/22156 to make sure the documentation is updated.

All 6 comments

While this behavior is definitely confusing, it's consistent with what string.Format does in the same situation, so I think this is the expected behavior.

Is there any meaningfull format-string which needs curly-braces?

The documentation you posted seems to be outdated. The current implementation does not print "{D}" (see here).

It works just as expected. Sample code:

Console.WriteLine($"{{{12:X}}}"); //prints "{C}"
````

which is lowered to:
```CSharp
Console.WriteLine(string.Format("{{{0:X}}}", 12));

And the final string is "{C}".

I looked up the implementation:

  • the first '}' terminates the format-string-part
  • '{' in the format-string would cause a "FormatError"

While this behavior is definitely confusing, it's consistent with what string.Format does in the same situation, so I think this is the expected behavior.

I dug around a little, and it turns out that documentation is out of date. (SharpLab)

The logic was changed to align with what people generally expect in .NET Core 3.0 in https://github.com/dotnet/coreclr/pull/23062. (Oddly enough it seems this wasn't reported on the list of breaking changes in .NET Core 3.0.)

It seems the Roslyn team never got the memo. It doesn't actually matter for the actual lowering because the format string isn't any different in the end, but the syntax tree represents things incorrectly.

@bernd5 @PathogenDavid I didn't know about that, thanks for teaching me something new. I have opened https://github.com/dotnet/docs/issues/22156 to make sure the documentation is updated.

Was this page helpful?
0 / 5 - 0 ratings