9

Possible Duplicate:
What's the use/meaning of the @ character in variable names in C#?

I was doing some .net development and I noticed I could add an @ symbol before any method call, i.e.:

var message = dog.@SayHello();

Just wondering, why is the reason this can be done ??

Community
  • 1
  • 1
Jose R. Cruz
  • 909
  • 2
  • 9
  • 15
  • 2
    http://stackoverflow.com/questions/91817/whats-the-use-meaning-of-the-character-in-variable-names-in-c – xdazz Aug 30 '11 at 15:23

5 Answers5

10

The @ symbol can escape keywords and turn them into ordinary identifiers. Most .net languages support a mechanism like this since keywords are language dependent, and thus code written in other languages might collide with a keyword in your language without even noticing it.

Some people like using @this for the first parameter extension methods.

public static void MyExtension(this MyType @this)

another scenario where this can be useful is when using members to represent html attributes. Then without this feature you could not represent the class attribute.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
6

An @ symbol can be pre-fixed to any identifier in case you're interoperating with code written in another language that uses C# keywords as identifiers:

object @class; //allowed
object class;  //error
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
6

This is simply part of the definition of a valid identifier in C#.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
3

@ lets you use an identifier that would otherwise be interpreted as a keyword.

For example, if you want to have a variable named class, you can write this:

int @class;

Of course, because you can do it doesn't mean it's a good idea to do it.

Some situations where it's useful is code generators that create C# code from a template or external source. e.g. xsd.exe is an SDK command-line tool creates C# classes that back up an XML schema. If your XML schema contains an element or attribute name that is reserved in C# (such as class), xsd.exe would preserve the name in the matching C# class but it would prefix it with a @.

Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
1

It's a case of just because we can, doesn't mean we should.

Eric Farr
  • 2,683
  • 21
  • 30