Keywords as variables/identifiers. Why?
Posted by Vadim on May 13, 2009
I use words variable and identifier interchangeably.
Have you ever tried to use a keyword as a name of your variable? Until recently I thought it was impossible. However, C# and VB.NET allow developers to use keywords as variables.
string string = '' '';Dim String As String = '' ''
If you try to compile this code, compiler will generate three errors:
- Error 1 Identifier expected; 'string' is a keyword
- Error 2 Identifier expected
- Error 3 Invalid expression term 'string'
To fix this error in C# you just prefix your variable with an @ character. In VB.NET you surround the variable with square brackets . A variable or identifier with an @ prefix is called a verbatim identifier.
string @string = '' '';Dim [String] As String = '' ''
Why anybody would use keywords as variables? To me it looks like a very BAD practice. Variables/identifiers must be descriptive. Can you think of any keyword that would be descriptive enough to use in your code as a variable?
I found in C# specification why Microsoft includes verbatim identifier in their languages:
The prefix "
@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character
@is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix.
I still believe it’s a BAD idea.
I also understand that if today I don’t see any reason to use verbatim identifiers, tomorrow I might find a perfect application for it.
If you use it and have a good reason, please let me know.