You don’t often come across a piece of Delphi code that uses the keyword “absolute”. A lot of Delphi programmers consider it to fall in that “stay away” category, like “goto”. The keyword, when used correctly can however be very convenient and improve the readability of your code.
The absolute keyword allows you to define a variable that points to the memory location of another variable. This is something you can achieve with pointers as well, but the absolute keyword allows you to do it very cleanly in a single line of code.
1 2 3 |
var SomeCtrl: TWinControl; MyForm: TForm absolute SomeCtrl |
The example above shows how you can use the keyword to forgo casting. Accessing MyForm would be like casting SomeCtrl to a TForm, but this way, you don’t have to bother doing the actual casting. It does of course it works for any type, not just objects.
Do be careful! Despite the fact that this is a very convenient way to shorten your code, you still have to do proper type checking before you use it! If in the example SomeCtrl wasn’t a TForm, using absolute won’t magically turn it into one.
1 2 3 4 5 6 7 8 9 |
var SomeCtrl: TWinControl; MyForm: TForm absolute SomeCtrl begin if SomeCtrl is TForm then begin // Access MyForm here end; end; |