I don't understand why this will not compile when typed out in a .cshtml/Razor page:
@($"{"\""}") // <-- does not work
@($"{"'"}") // <-- does not work
@($"{"a"}") // <-- works
The error states:
RZ1000: Unterminated string literal. Strings that start with a quotation mark (") must be terminated before the end of the line. However, strings that start with @ and a quotation mark (@") can span multiple lines.
CS1002: ; expected
CS1513: } expected
It appears that non-quote characters work fine, but a double-quote or single-quote character breaks Razor's ability to parse the interpolated string, even when the quote character is escaped.
All the examples work fine in a plain .cs file:
public sealed class Test
{
public string x = $"{"\""}";
public string y = $"{"'"}";
public string z = $"{"a"}";
}
What gives?
My environment is as follows:
.NET SDK: v7.0.102
.NET Runtime: v7.0.2
C#: v11 (preview)
Visual Studio Community 2022 (64-bit): v17.4.4
Update
This bug is now being tracked here:
https://github.com/dotnet/razor/issues/7084
It's a bug, known by the .NET guys as far back as 2015 at least.
The dotnet engineers on the dotnet/aspnetcore github page felt the work required to fix it outweighed the benefits, however:
Jun 3, 2015
After investigating this issue further turns out the requirements to complete this are pretty high (need to understand C# close to entirety at the Tokenizer level). Will revisit this later.
10 weeks and 2 days later...
Aug 14, 2015
Moving to backlog because we feel these cases are not common in MVC views, and have trivial workarounds (e.g. use string.Format() instead of string interpolation).