Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why built-in types in C# are language keywords?

In C#, identifiers such as int or string are actually language level keywords.
What is the reason for that?

Note that if the authors wanted to disallow user types with these names, that could have made that a semantic error, not syntax error.

Some clarifications based on answers:

  1. They are keywords because it makes parsing possible/easier
    I do not see why, as I am developing a parser, and having Type.Rule = Identifier is much simpler than Type.Rule = Identifier | "int" | "string" | ....

  2. They are keywords because they are special aliases
    var and dynamic are special things as well, but not keywords (for compatibility reasons, nevertheless it demonstrates that being a keyword is not necessary to be special). In a different example, applying [Serializable] to a type produces magic IL metadata modifier serializable instead of standard custom attribute. But it is still not a keyword.

  3. They are keywords because they were keywords in other languages
    Good answer, but then, why are they keywords in other languages? Also, it is certainly possible to highlight them in blue without them being keywords, so why bring that in from other languages?

like image 546
Andrey Shchekin Avatar asked Jul 21 '12 10:07

Andrey Shchekin


1 Answers

As far as I've read, the C# designers wanted to allow the typical type names as they are usual in C-style languages, namely string, int, and so on. At the same time, each of these types has to have a full-qualified type names such as System.String and System.Int32. Therefore, it was decided to provide aliases for these frequently used types.

If I find the source for this statement again, I'll add the link.

In other CLI-based languages, the same full-qualified type identifiers are valid. However, type names such as int or string might not be usual in such languages, so other aliases might be provided there.

One possible advantage of using the type alias may be improved readability, which is why there is a StyleCop rule that enforces use of the alias over the regular type name. The point about brevity is also mentioned in this thread on the same topic.

like image 171
O. R. Mapper Avatar answered Oct 17 '22 16:10

O. R. Mapper