Aspnetcore: Creating anonymous object starting with @class creates compiler error

Created on 15 Oct 2019  路  3Comments  路  Source: dotnet/aspnetcore

Describe the bug

In a Razor page, creating an anonymous object (eg. for HtmlAttributes) starting with @class inside a @{} block creates these compiler errors

(void?): class" is a reserved word and cannot be used in implicit expressions. An explicit expression ("@()") must be used

and

CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

and

CS1525: Invalid expression term '='
image

To Reproduce

Steps to reproduce the behavior:

  1. Using Razor in a ASP.NET Core 3.0 project
  2. In Startup.cs, add services.AddRazorPages().AddRazorRuntimeCompilation();
  3. Create a cshtml view

Code that creates error

@{ var htmlAttributes = new { @class = "form-control" }; }

Working code

@{ var htmlAttributes = new { foo = "bar", @class = "form-control" }; }

Won't Fix area-mvc bug

All 3 comments

You can use double @@
PreserveNameRazor

@fehrm Thanks for contacting us.

@NTaylorMullen The double @@ shouldn't be necessary as you are already inside a c# context, am I wrong? Otherwise @soeleman answer is correct.

Thanks for contacting us, @fehrm.
While this is a bug, it's super low pirority and we won't spend time fixing it, as the workaround is to simply use @@ per @soeleman's suggestion.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

markrendle picture markrendle  路  3Comments

rbanks54 picture rbanks54  路  3Comments

ermithun picture ermithun  路  3Comments

guardrex picture guardrex  路  3Comments

bgribaudo picture bgribaudo  路  3Comments