views:

161

answers:

2
+6  Q: 

C# strudel sign

While coding in C#, I by mistake added a strudel sign before a variable in if statement (instead of exclamation mark).

bool b = false;
if (@b)
{

}

I surprised it compiled successfully without any error.

I wonder: What is the meaning of the above code?

+13  A: 

@ can be used to "escape" identifiers, in case you want to use keywords. For example:

int @class = 10;

Of course it's usually a bad idea to use keywords as identifiers, but if you're using a class library which happens to use them, it can be hard to avoid. It can also be useful sometimes to use "@this" for situations where you want to effectively have a this reference, but for whatever reason you can't use one. (These are pretty few and far between, but I've seen it a couple of times, and it's worth at least knowing about.)

Jon Skeet
+9  A: 

Jon's answer sums it up. An example of when you must use this technique of escaping is specifying HTML attributes in anonymous types to helper methods in ASP.NET MVC.

Html.ActionLink("text", "action", "controller",
    new { @class = "some-css-class" }, null);

I've also hit this when composing anonymous types for posting via HTTP using JSON encoding, where you cannot modify the remote API.

+1 for 'strudel' too :)

Drew Noakes