Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does placing a @ in front of a C# variable name do? [duplicate]

Tags:

c#

It's just a way to allow declaring reserved keywords as vars.

void Foo(int @string)

It allows you to use a reserved word, like 'public' for example, as a variable name.

string @public = "foo";

I would not recommend this, as it can lead to unecessary confusion.


Putting @ in front of a string tells the compuler not to process escape sequences found within the string.

From the documentation:

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

To include a double quotation mark in an @-quoted string, double it:

@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

Another use of the @ symbol is to use referenced (/reference) identifiers that happen to be C# keywords. For more information, see 2.4.2 Identifiers.


This escapes reserved words in C#.


The original question asks for a reason why one would escape a not-reserved word. What comes to my mind is that if step would become a reserved word in future the code example would still compile. I guess it is also a valid option for code generators.


The @ sign is used with identifiers that are the same as language keywords. There are two main uses for this - interoperating with non-C# code. In languages like VB or IronPython the keywords are not the same as in C# and they may have declared classes and properties with names that match C# keywords. If this feature was not present this code would not be accessible in C#. - machine generated code. If a code generator generates code based on some external source (for example WSDL) the generator can just prefix all identifiers with @ and not check and convert identifiers that match C# keywords.

Are you sure that your case is not the second?