1

Possible Duplicate:
What does placing a @ in front of a C# variable name do?

Hi,

I justed picked up on Silverlight and RIA services. While creating a new domain service which supports editing, the following code was generated in the domain service class (C#):

  public void InsertClass(Class @class){
        ...
  }

What is the significance of the @ symbol in the variable name?

Community
  • 1
  • 1
Ryan
  • 26,884
  • 9
  • 56
  • 83

6 Answers6

6

class is a reserved word in C# to denote a new type. You can't have a variable name that is a reserved word, so you use @ to 'escape' the symbol.

AKA:

int int = 4; // Invalid
int @int = 4; // Valid
Tejs
  • 40,736
  • 10
  • 68
  • 86
1

The @ is used in cases where you have to have a variable name that's also a c# reserved keyword. In most cases it can be avoided (and should be, because of the confusion it can cause). Some times it's unavoidable; for instance in asp.net MVC you have add css class to an element you have to use an anonymous class like this

new {@class = "myCssClass" }

for it to render

... class="myCssClass" ...

There's no way around it.

Bala R
  • 107,317
  • 23
  • 199
  • 210
1

what would happen if you tried to name a variable class, do you think? The @ prefix lets you use reserved/key words as variable names.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
1

This was answered previously here.

The @ symbol allows you to use reserved word.

Community
  • 1
  • 1
Chad
  • 19,219
  • 4
  • 50
  • 73
1

The @ sign is valid only at the beginning of a variable name and is used to allow reserved keywords to be used as variable names.

var @class = 12;  // This will compile
var cl@ss = 12; // This will NOT compile
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
1

The @ symbol is used when you want to name variables that are also C# keywords. i.e.,

var @abstract = "1234";

would create a string called "@abstract". If you did not you would get a compile error.

Also - you can use the @ sign in front of strings:

var myStr = @"C:\MyDataFile.txt";

This way, you don't have to escape literals inside the string. Normally you would have had to use a double \ after C:

Seph
  • 8,472
  • 10
  • 63
  • 94
Matthew M.
  • 3,422
  • 4
  • 32
  • 36