Monday, April 11, 2011

Using C# keywords as variables

Hold it, don't shoot me. I know this would be an awful practice, but it is an interesting C# compiler quirk nonetheless.
Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.
static void Main(string[] args) {           
    var @if = "oh my..";

========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========


  1. Are more useful scenario is adding a css class to a hyperlink using the ActionLink HtmlHelper in ASP.NET MVC. Since "class" is a reserved keyword, you wouldn't normally be able to use it while instantiating a dictionary. "@" to the rescue!

    Html.ActionLink("Some Text", "SomeAction", new { @class = "class-name" })

  2. Oh, nice real-world scenario :)

  3. Same thing with "checked", as used in HTML checkboxes

  4. The most awesome thing about using keywords as variables is when you have to use someone's WSDL for service class generation and they used keywords everywhere. Prefix them with @ and it works. Too bad visual studio doesn't do that automatically.

  5. i've seen some @if, @else in F# source code

  6. Thanks!!! Its helpful for me :)
    -Mehul Mehta (Ahmedabad)