Saturday, May 19, 2007

DN4DP#9: Escaping keywords

This post continues the series of The Delphi Language Chapter teasers from Jon Shemitz’ .NET 2.0 for Delphi Programmers book. Last time we covered the internationalization of Pascal identifiers. This time we will see how you can use imported identifiers that conflict with Pascal keywords.

Note that I do not get any royalties from the book and I highly recommend that you get your own copy – for instance at Amazon.

"Escaping keywords

All programming languages have certain keywords reserved - meaning they cannot be used as user defined identifiers. However, since .NET is inherently a multi programming language platform, each language needs to have a mechanism to import and use any identifier.

In Delphi, you can prefix an identifier with an ampersand (&) to have it interpreted as an identifier and not a language keyword. All Delphi keywords (or reserved words) are listed in the online documentation.

If the keyword identifier is the name of a type, you can often avoid using the escape character by fully qualifying the type name with its namespace. From the EscapingKeywords project

var 
T1: &Type;
T2: System.Type;
A1: &Array;
A2: System.Array;

If the keyword identifier is a member of an instance you must use the escape character. For instance

var 
HR: HttpResponse;
begin
//...
HR.&End;

If you are in the mood you can even declare your own type or member identifiers that are keywords. One silly example is

type 
&resourcestring = string;
&Begin = class
&for: &resourcestring;
procedure &Goto(&if: &resourcestring; &is: &resourcestring);
function &End: &resourcestring;
end;




Tip:    The ampersand (&) escape can also be used to turn off Delphi's special mapping of the Create identifier to a constructor. To call a method called Create you must use &Create.


"

No comments:



Copyright © 2004-2007 by Hallvard Vassbotn