views:

163

answers:

5

Hi,

I'm browsing the source code of StyleCop, and I found a curious thing:

/// <summary>
/// The namespace that the rule is contained within.
/// </summary>
private string @namespace;

// [...]

internal Rule(string name, string @namespace, string checkId, string context, bool warning) : this(name, @namespace, checkId, context, warning, string.Empty, null, true, false)
{
    Param.Ignore(name, @namespace, checkId, context, warning);
}

What is this thing? Is it just a simple field where at-sign is used to indicate that it is a field, and not a namespace keyword? If so, may at-sign be used for any reserved word (for example @dynamic, @using, etc.)?

+4  A: 

Yes @ sign may be put in front of reserved words to allow them to be used as variable names.

var @dynamic = ...
var @event = ....

I actually learned that, and other things, from this question

Mike Two
+5  A: 

Hi there.

Bascially yes. Putting a @ in front of the variable name stops an error ocurring due to that variable name being a keyword.

http://msdn.microsoft.com/en-us/library/x53a06bb(VS.71).aspx

Jason Evans
What is the difference from putting an underscore (or any other character) in front?
adrianm
@adrianm: the difference I've found is that when using reflection, `FieldInfo.Name` if `@namespace` will be 'namespace', whereas the name of `_namespace` will be '_namespace'.
MainMa
A: 

Yes, you can use @ as the first and only first character of your variable.

Mike
A: 

As the other people answered, exactly, you can use reserved keywords as long as you prefix then with '@', but IMHO, that's not a good development practice. I'd rather use it only in machine generated code (for instance, in the company I work for, we have a tool that converts Java code to C#; since in Java "event" is not a reserved word, our Java source code may contain such identifiers)

Best

Adriano

Vagaus
+1  A: 

This technique is usually paired with automatic code generation, as identifiers may be produced that are keywords in a target language, e.g. if an Xml schema has code generation run over it to produce C# classes, the schema may have an attribute called "event". This is a C# keyword, so the code generator can instead use "@event".

chibacity