18

Possible Duplicates:
What does the @ symbol before a variable name mean in C#?
What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

protected void Method1(Type1 @arg1, Type2 arg2)
...

I use c# with .net 3.5.

Thanks.

Community
  • 1
  • 1
iburlakov
  • 4,164
  • 7
  • 38
  • 40
  • 1
    It's an escape character that allows you to use reserved words as identifiers. This question gets asked a lot. See: http://stackoverflow.com/questions/429529/what-does-the-symbol-before-a-variable-name-mean-in-c – Cody Gray - on strike Jan 19 '11 at 14:18

4 Answers4

27

It allows reserved words to be used as identifiers. It is usually used by code generators which may be using source names from systems with different keywords than the target language e.g. table names and sproc argument names.

Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
  • 1
    @BoltClock: Yeah, sometimes it's used superfluously. I can only imagine the programmer who originally does this has no idea what it means, but saw it somewhere and thought it looked cool. Or, as the answer points out, this is sometimes done by automatic code generators. – Cody Gray - on strike Jan 19 '11 at 14:19
  • 2
    @BoltClock No it is not, but the code generator does not know that. Code generators often place the @ symbol in front of all identifiers. – Tim Lloyd Jan 19 '11 at 14:19
8

It is a way of escaping an identifier.

E.g. the following two are equivalent:

protected void Method1(Type1 @arg1, Type2 arg2)
protected void Method1(Type1 arg1, Type2 arg2)

@ is only really usefull if you need to name an identifier after a keyword. The below would not compile without the @:

protected void Method1(Type1 @class, Type2 arg2)

Andrew Skirrow
  • 3,402
  • 18
  • 41
3

For your specific example, it has no meaning. In C#, the @ symbol is used to escape keywords so that they can be used as variable names.

For instance, the following would generate a compiler error:

public void Test(string class){...}

But if you escape with @, it is fine:

public void Test(string @class){...}
Brian Ball
  • 12,268
  • 3
  • 40
  • 51
3

It is used to have reserved words as parameters. Example:

string @string = "abc";

or:

string @class = "foo";

arg1 is not a reserved word so using @ is not necessary. This being said, using reserved words to name your parameters is not a good idea. There are cases though where this is useful. For example in ASP.NET MVC some HTML extension methods take an anonymous object as parameter to emit html attributes. So you have syntax like this:

<%= Html.ActionLink("text", "action", "controller", null, new { @class = "abc" }) %>

which generates:

<a href="/controller/action" class="abc">text</a>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928