Wednesday, October 25, 2006

Escape characters to use reserved words as variable names in .NET

This post is a follow up to Jean-Paul's article: Naming variables using the variable type name (useless tip #1), from the MSDN documentation we get this (at the top of the C# keywords section)

Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.

.NET solved what was one of the biggest problems in the development area, which was seamless language interaction (because now every language compiles down to Intermediate Language).

Today in .NET you can write code in any .NET language and use it in any other .NET language; however, this does bring one issue, which is that reserved words in one language may not mean anything in other language, for example you might be programming in C# and you could call a variable begin, which in Delphi is a reserved word, and so when they used your C# code from Delphi they couldn't use it; to solve this problem, languages should (for their own good) implement some kind of escape character that allows you to use reserved words as variable names in case you are using code that was written in another language and they declared a variable name with the name of a reserved word in the language you are using

in C# you use the @ prefix

string @while = "something"
Console.WriteLine(@while);

in Delphi you use the & prefix

&begin:Integer;
begin
&begin := 10;
Console.WriteLine(&begin);

in VB.NET you use brackets to delimit the keyword

Dim [Dim] = 20
Console.WriteLine([Dim])

let me know if you know the escape character for other .NET languages

p.s. just noticed Jeff calls them escaped identifiers


kick it on DotNetKicks.com

1 comment:

Anonymous said...

you have a good blog, good job,I think we could link to our blogs and have a link exchange, if you're agree with me please email me to make a connection through our blogs.you could find about me in my profile or check lines below:
my blogAddress is http://babaeian.blogspot.com/
emai"l: hipersia@gmail.com