The "@" character is allowed as a prefix to enable keywords to be used as identifiers. Majority of .net developers know about this.
But what we may not know: Two identifiers are considered the same if they are identical after the "@" prefix is removed.
So
static void Main(string[] args) { int x = 123; Console.WriteLine(@x); }
is absolutely valid code and prints 123 to the console.
I'm curious why do we have such rule in the specs, and how this feature may be used in real world situations (it doesn't make sense to prefix identifiers with "@" if they are not keywords, right?).
"Identifiers" or "symbols" are the names you supply for variables, types, functions, and labels in your program. Identifier names must differ in spelling and case from any keywords. You cannot use keywords (either C or Microsoft) as identifiers; they are reserved for special use.
language documentation Syntax Identifiers are grammatical building blocks that may be used to give a name to entities/objects such as constants, variables (e.g. Scalar s) and routines (e.g. Sub s and Methods). In a variable name, any sigil (and twigil) precedes the identifier and does not form a part thereof.
Characters in identifiers The first character in an identifier must be a letter or the _ (underscore) character; however, beginning identifiers with an underscore is considered poor programming style. The compiler distinguishes between uppercase and lowercase letters in identifiers.
It is totally logical. @
is not part of the name but is a special indicator to not treat what comes after as a keyword but as an identifier.
Eric Lippert has a very good post about it: Verbatim Identifier
I’m occasionally asked why it is that any identifier can be made into a verbatim identifier. Why not restrict the verbatim identifiers to the reserved and contextual keywords?
The answer is straightforward. Imagine that we are back in the day when C# 2.0 just shipped. You have a C# 1.0 program that uses yield as an identifier, which is entirely reasonable; “yield” is a common term in many business and scientific applications. Now, C# 2.0 was carefully designed so that C# 1.0 programs that use yield as an identifier are still legal C# 2.0 programs; it only has its special meaning when it appears before return, and that never happened in a C# 1.0 program. But still, you decide that you’re going to mark the usages of yield in your program as verbatim identifiers so that it is more clear to the future readers of the code that it is being used as an identifier, not as part of an iterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With