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:
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" | ...
.
They are keywords because they are special aliasesvar
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.
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?
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.
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