I just found myself absent-mindedly using from
as an identifier.
I realise that it is possible to use @
to escape identifier names and as such use reserved words, but I don't understand why in this case I got no warning or error.
I have no desire to use reserved words for anything but their intended purpose, but I don't w开发者_开发问答ant to make a similar mistake again and would like to know the rationale behind having language keywords that are not reserved in certain circumstances.
Some keywords are only reserved in certain contexts, e.g., the partial
in partial class
.
See the "contextual keywords" under this topic on MSDN.
The C# team specifically tries to avoid creating new reserved keywords in the language. Any new keyword added means that it automatically breaks existing code which used that keyword as an identifier. Hence whenever possible C# will use a contextual keyword to minimize or eliminate the possibility of breaking existing code.
A contextual keyword is one that is only a keyword when used in a specific context like from
, partial
, var
, etc ... That context does not include identifiers :)
I do not believe there's been a new keyword added since C# 2.0 (not even sure 2.0 added one)
from is a 'contextual keyword'. Lots of those in C#, they only behave like a keyword when they are used in a certain context. The big advantage is that adding such a contextual keyword to the language won't break existing code.
You'll find them listed in the 2nd table in this MSDN page. Yup, from is there.
They are not reserved when they are contextual (MSDN link):
A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.
To answer the underlying question:
All keywords added after C# 1 are contextual. This avoids breaking changes.
Almost all C# 1 keywords are reserved, except for accessor keywords (add
, remove
, get
, and set
).
Most of the C# keywords are always reserved. Some, as you found out, is only reserved in some contexts. They are called contextual keywords. I believe this is a way to better ensure backwards compatibility.
The reasoning is that from
was a perfectly acceptable variable name in C# 2. C# 3 added LINQ, and they needed keywords for it. In order to maintain maximum compatibility, from
was added as a contextual keyword.
精彩评论