100

Possible Duplicate:
What does the @ symbol before a variable name mean in C#?

Duplicate:

What does the @ symbol before a variable name mean in C#?

Sometimes I see some C# code where a method-parameter is prefixed with an @, like this:

public static void SomeStaticMethod( SomeType @parameterName ) { }

What is the meaning of this ? Does it has some significant special meaning ?

I am creating an EventListener in NHibernate, and when I let VS.NET generate the interface methods, it generates the OnPostLoad method like this:

public class PostLoadEventListener : IPostLoadEventListener
{
    public void OnPostLoad( PostLoadEvent @event )
    {

    }
}

Why is this ?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • 2
    This is one of those questions that come up reguralry and we could put into a tag-specific FAQ, check the relevant uservoice ticket: http://stackoverflow.uservoice.com/pages/1722-general/suggestions/138261-allow-a-per-tag-home-faq-page – Tamas Czinege Jun 24 '09 at 14:22

3 Answers3

144

Try and make a variable named class and see what happens -- You'll notice you get an error.

This lets you used reserved words as variable names.

Unrelated, you'll also notice strings prefixed with @ as well -- This isn't the same thing...

string says = @"He said ""This literal string lets me use \ normally 
    and even line breaks"".";

This allows you to use 'literal' value of the string, meaning you can have new lines or characters without escapes, etc...

hugoware
  • 35,731
  • 24
  • 60
  • 70
52

The @ prefix allows you to use reserved words like class, interface, events, etc as variable names in C#. So you can do

int @int = 1
Rad
  • 8,336
  • 4
  • 46
  • 45
23

event is a C# keyword, the @ is an escape character that allows you to use a keyword as a variable name.

Timothy Carter
  • 15,459
  • 7
  • 44
  • 62
  • 18
    Which is probably a bad idea... – Dervin Thunk Jun 24 '09 at 14:22
  • 2
    I know I always avoid doing this, but it is an available feature. – Timothy Carter Jun 24 '09 at 14:23
  • 6
    Dervin: There are cases when you can't really avoid it, such as interfacing with assemblies written in other languages or previous versions of C#. – Tamas Czinege Jun 24 '09 at 14:24
  • 3
    But at the same time kinda necessary when you cannot predict what new keywords may be introduced in future versions of the language... you may after all have a pre 4.0 library that uses 'dynamic' as a symbol name, which you otherwise would no longer be able to fully access from a 4.0 application... – jerryjvl Jun 24 '09 at 14:25
  • 2
    Since C# 1.0 no new reserved words have been added, only contextual keywords. This will be the case with dynamic as well. http://blogs.msdn.com/ericlippert/archive/2009/05/11/reserved-and-contextual-keywords.aspx – Timothy Carter Jun 24 '09 at 14:43