PeterT
PeterT

Reputation: 1464

When are C# keywords not reserved?

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 want to make a similar mistake again and would like to know the rationale behind having language keywords that are not reserved in certain circumstances.

Upvotes: 8

Views: 831

Answers (6)

SLaks
SLaks

Reputation: 887415

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).

Upvotes: 1

driis
driis

Reputation: 164291

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.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941427

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.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754675

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)

Upvotes: 4

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

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.

Upvotes: 2

Stephen Cleary
Stephen Cleary

Reputation: 456457

Some keywords are only reserved in certain contexts, e.g., the partial in partial class.

See the "contextual keywords" under this topic on MSDN.

Upvotes: 13

Related Questions