Developing on Staxmanade

How can C# variable have an @ sign in front of it?

I remember a year ago I noticed in some code a coworker put together had a variable with an @ sign in front of it. At first I was baffled that it even compiled. I asked my c-worker about it and he said he had no clue as to why it was there and what it was for... so then I spent some time googling and couldn't find anything on the net describing this and why it compiled.

basically what I'm talking about is if you have some code

private void MyMethod(string myparam)
{
    int a = @myparam.Length;
}

Notice the @ sign in front of the myparam variable... That is what I saw in my co-workers code and I couldn't explain how that worked...

now, nearly a year later I was perusing through the SLUnity framework on codeplex [] and saw the @ sign again...

public void UnregisterSubscriber(string publishedEventName, EventHandler subscriber)
{
    PublishedEvent @event = GetEvent(publishedEventName);
    @event.RemoveSubscriber(subscriber);
    RemoveDeadEvents();
}

I did some more googling and still can't find anything, (I'm sure it's out there, just can't put together the right search criteria)...

Then I went back to the code, looked at it for a minute, and it dawned on me that "event" is a keyword in c#... Then I thought, maybe this is what you can do to use a C# keyword in another context than the desired reason to have the keyword.

So I wrote a little test to see if this hypothesis was correct.

private static void MyMethod(string class)
{
    int a = class.Length;
}

this won't compile because of the "class" keyword...

then I put the @ sign in front of class

private static void MyMethod(string @class)
{
    int a = @class.Length;
}

and it not only compiled, but you also get intellisense on the variable...

How cool...

I'm not sure I would do that on a regular basis, seems like it might be a bit of a pain to write... However maybe framework code may need to have this to allow it to be more readable to it's consumers? Anyone know why on this?

Comments

Anonymous
nice one :), had me fooled for a bit too when I found a variable named @@delegate
Justin Chase
That is exactly what it is for, so you can use reserved words for variable names. You'll see this in some of the .NET framework even, with method parameters named @object in some places. I suspect it was added to C# specifically to be compatible with libraries written in other languages so that when it generates methods for you and uses the defined parameter name it won't have a compile error if it happens to be a C# keyword.