1

Closed

@-Named C# Variables + Nested Blocks Generate Broken Code

description

The following code, when inserted into a .cshtml content page, generates a .cs file with a brace mismatch:
@{
    int @int = 0;
    
    if (true)
    {
        int lTest = 0; 
    }
}
In C#, in order to create a variable/property/function with the same name as a C# keyword, you prefix the identifier with the @ symbol. When used inside a Razor code block, with a nested block between the @-prefixed identifier and the end of the razor block, it also causes the code generator to end the Razor block early:

Image

The closing brace of the nested block is detected as the end of the Razor block, and the closing brace of the Razor block is output as raw HTML, with the net result that a closing brace that should exist in C# to be compiled is not present, at which point the compiler logs a } expected error.

Image

The logged error is for a generated .cs file, not the .cshtml file with the @ in it, and does not indicate that the @ is to blame for the problem, making it un-intuitive to debug for users.

This issue only occurs if the @ is not the first character in a statement. If the @ is the first character in a statement, the code generator logs the a useful Once inside code, you do not need to prefix constructs with "@". error.

This issue only occurs if the @ is used to prefix an identifier. If used to create a multi-line string, for example, it does not cause early termination of the Razor block.

This issue only occurs if there exists a nested block between the @ and the end of the Razor block, designated by { and } braces.

This issue occurs regardless of what kind of nested block is between the @ and the end of the Razor block. Confirmed for using blocks, if blocks, for blocks, try blocks, and array initialization blocks.

This issue occurs regardless of what kind of Razor block the container is. Confirmed for @{ } blocks, @if blocks, and @foreach blocks.
Closed May 7 at 10:16 PM by yishaigalatzer
Thanks for reporting, we are aware of this issue and it's a known limitation.

We are not intending to fix. But we are planning to clearly document the limitation.

comments