Why can I create a class named "var"?

var is not a keyword according to this list.

it is a contextual keyword, so from the context, the compiler is able to decide which is your class and which is the contextual keyword, and no confusion arises.

a contextual keyword is:

used to provide a specific meaning in the code, but it is not a reserved word in C#.

so as it's not reserved you can use it.

As pointed out in the comments above there is a discussion of the differences as well as a list of the various keywords and contextual keywords added at each version of c# on Eric Lippert's blog

It is interesting to note that since the set of keywords was decided upon in C#1.0 there have been no additions, so as to preserve backward compatibility.


Another way of looking at this: "var" as a keyword was not in the first versions of C# (unlike "int" and "true"), so you might have written some code then which had a class called "var". This was perfectly fine and legal. Then later on when "var" was added to the language, the designers were so kind as to make it a keyword only in certain contexts, so your existing var class would still work.

This is one of the real challenges of language design - how to add new features without breaking existing code, and without making the new features cumbersome to use.


The compiler is smart enough to know that the context you are using var as a class name is never a context for the keyword so allows it (which is why it is defined as a contextual keyword).

Tags:

C#

.Net 4.0