dotnet/roslyn

C# string interpolation has poor error recovery

Open

#3,771 opened on Jul 1, 2015

View on GitHub
 (2 comments) (0 reactions) (0 assignees)C# (20,414 stars) (4,257 forks)batch import
Area-CompilersBugConcept-Diagnostic ClarityLanguage-C#help wanted

Description

Consider following C# expression

$"{HttpStatusText}{string.IsNullOrEmpty(MessageStatusText) ? "" : " - "}{MessageStatusText}"

It is not valid because C# parser treats ":" as format separator instead as of part of ternary operator (IMO it's suboptimat behavior of parser, but that's separate story). When the compiler encounters this expression it generates 4 errors: CS8076 Missing close delimiter '}' for interpolated expression started with '{'. CS1003 Syntax error, ':' expected CS1733 Expected expression CS8088 A format specifier may not contain trailing whitespace. Which is quite confusing and initially I thought that i discovered sever bug in the parser, before I understood what actually is wrong. I think that for one issue parser should generate just one message. This issue is impossible to fix following the hints given by error messages. It's especially confusing when compiler tells me for the exact position of ":" "Syntax error, ':' expected". It would be more helpful to provide some message that would guide devloper to fix. Also the 1st error is reported one more character left that it should be (it's reported for "}").

Note: The correct version of the expression is

$"{HttpStatusText}{(string.IsNullOrEmpty(MessageStatusText) ? "" : " - ")}{MessageStatusText}"

Observer in VS2015 RC

Contributor guide

C# string interpolation has poor error recovery · dotnet/roslyn#3771 | Good First Issue