AKA Silly Delphi Party Tricks #1
Is it possible to use a reserved word as an identifier ?
For example – I want to name my variable or class “BEGIN” because, ummm, well I dont know just because.
Yes you can. Simply prefix the the name with an ampersand “&” escape character like this
var &begin : integer; // begin is a reserved word begin &begin := 123; end;
That doesn’t mean its a good idea. This is mainly useful to impress your friends at parties with your astounding knowledge of Delphi quirks.
Delphi doesnt always play nicely with this language feature. I dont mean it will crash – I just mean sometimes it will display the ampersand and sometimes it wont. For example if you add a breakpoint then view the variable in the debugger it will be show as &BEGIN.
However, if you show the name of a class based on a reserved word at runtime it removes the ampersand
-- the name of this class is a reserved word "begin" type &begin = class(TForm) private foo : integer; end; begin ShowMessage ('The class name is ' + &begin.ClassName + #10 + 'length of class name = ' + &begin.ClassName.Length.ToString ); end;
When the code is run, the class name “begin” is displayed (no ampersand).
The length is 5, which verifies the name BEGIN is being used and the ampersand escape character is not stored in the name.
Is this used in Delphi’s own source code ?
You would think that this technique would be avoided in the Delphi source code but actually it is used in at least these 36 units (in Delphi 10.1) and probably more.
|Delphi Unit||Reserved Word
used as a procedure,
function or property
|FMX.Platform.Mac||TYPE and SET|
|IdFTPListParseStercomOS390Exp||ARRAY and SET|
|System.Android.Notification||ARRAY, OBJECT, TYPE|
|System.Threading||ON, STRING, TYPE|
Good enough for Delphi, good enough for me ?
By now you are thinking “hey, if its ok for this to be used in the source code of Delphi itself, surely it is ok for me to use this technique”.
Nahhhhh, dont be silly. The technique works, but that doesn’t mean it’s a good idea to use it. I think you should only use this in desperation. For example, writing code that has to closely match some other code or interface that is outside of your control.
Even in those scenarios, I prefer to prefix or suffix an underscore to the name to make it clear that I am avoiding the use of a reserved word. Like this :
type HokeyPockey = class (TForm) private public _in : boolean; _out : boolean; InOut : boolean; ShakeItAllAbout : boolean; end;
+1 this post
About The Author
The Usual Suspect
– Scott Hollows –
- Oracle and Delphi software developer.
- Australian Delphi User Group – Western Australia Chief Cat Herder
- Australian Delphi User Group – President