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..";
 
    Console.WriteLine(@if);
}

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

6 comments:

  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" })

    ReplyDelete
  2. Oh, nice real-world scenario :)

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

    ReplyDelete
  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.

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

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

    ReplyDelete