It is not possible to extend a class with any method or property. There are some restrictions on the
possibilities:
- Destructors or class destructors are not allowed.
- Class constructors are not allowed.
- Record helpers cannot implement constructors.
- Field definitions are not allowed. Neither are class fields.
- Properties that refer to a field are not allowed. This is in fact a consequence of the
previous item.
- Abstract methods are not allowed.
- Virtual methods of the class cannot be overridden. They can be hidden by giving them
the same name or they can be overloaded using the overload directive.
- Unlike for regular procedures or methods, the overload specifier must be explicitly
used when overloading methods in class helpers.
The following modifies the previous example by overloading the ToString method:
TObjectHelper = class helper for TObject
function ToString(const aFormat: String): String; overload;
end;
function TObjectHelper.ToString(const aFormat: String): String;
begin
Result := Format(aFormat, [ToString]);
end;
var
o: TObject;
begin
Writeln(o.ToString(’The object’’s name is %s’));
end.