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
  • 24,944
  • 9
  • 54
  • 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
  • 39,976
  • 10
  • 65
  • 85
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
  • 104,615
  • 23
  • 192
  • 207
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
  • 65,549
  • 13
  • 92
  • 133
1

This was answered previously here.

The @ symbol allows you to use reserved word.

Community
  • 1
  • 1
Chad
  • 18,660
  • 4
  • 47
  • 71
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
  • 24,976
  • 13
  • 86
  • 117
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,224
  • 10
  • 61
  • 91
Matthew M.
  • 3,382
  • 4
  • 31
  • 36