Reputation: 248
I am working with asp.net mvc and creating a form. I want to add a class attribute to the form tag.
I found an example here of adding a enctype attribute and tried to swap out with class. I got a compile error when accessing the view.
I then found an example of someone adding a @ symbol to the beginning of the property name and that worked. Great that it works, but I am one that needs to know why and a quick Google search was not helpful. I understand that C# allows one to prepend the @ to a string to ignore escaping chars. Why does it work in this case? What does the @ tell the compiler?
Code that produces a compile error?
<% Html.BeginForm("Results", "Search",
FormMethod.Get, new{class="search_form"}); %>
Code that does work:
<% Html.BeginForm("Results", "Search",
FormMethod.Get, new{@class="search_form"}); %>
Upvotes: 19
Views: 621
Reputation: 35861
In C#, 'class' is a reserved keyword - adding an '@' symbol to the front of a reserved keyword allows you to use the keyword as an identifier.
Here's an example straight out of the C# spec:
class @class {
public static void @static(bool @bool) {
if (@bool) System.Console.WriteLine("true");
else System.Console.WriteLine("false");
}
}
Note: this is of course an example, and not recommended practice.
Upvotes: 37