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"}); %>
-
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.
GrillerGeek : I guess that would make sense. I was looking way too deep to find the answer to this one.Erik Forbes : I know how you feel. =)Daniel Brückner : Nice! I was not aware of that ... +1Michael Meadows : example code is way scary! class @class, bool @bool, switch (@switch). Fun to be had with class @struct, or bool @int... It make this possible: public static @static @static;bendewey : +1 learning things on SO.Erik Forbes : Yeah - definitely a readability nightmare if taken to the extreme like the example.
0 comments:
Post a Comment