10.1 Definition

Class and record helpers can be used to add methods to an existing class or record, without making a derivation of the class or re-declaring the record. The effect is like inserting a method in the method table of the class. If the helper declaration is in the current scope of the code, then the methods and properties of the helper can be used as if they were part of the class declaration for the class or record that the helper extends.

The syntax diagram for a class or record helper is presented below.

_________________________________________________________________________________________________________
Helper type

 ---class----helper------------------for-Identifier-helper component list
  - record -|        -( -basehelper )-|           -------------------|
----end - hint modifiers---------------------------------------------

--helper component list|-method definition-----------------------------
                    -property definition-
___________________________________________________________________

The diagram shows that a helper definition looks very much like a regular class definition. It simply declares some extra constructors, methods, properties and fields for a class: the class or record type for which the helper is an extension is indicated after the for keyword. Since an enumerator for a class is obtained through a regular method, class helpers can also be used to override the enumerators.

As can be seen from the syntax diagram, it is possible to create descendents of helpers: the helpers can form a hierarchy of their own, allowing to override methods of a parent helper. They also have visibility specifiers, just like records and classes.

As in an instance of the class, the Self identifier in a method of a class helper refers to the class instance (not the helper instance). For a record, it refers to the record.

The following is a simple class helper for the TObject class, which provides an alternate version of the standard ToString method.

TObjectHelper = class helper for TObject  
  function AsString(const aFormat: String): String;  
end;  
 
function TObjectHelper.AsString(const aFormat: String): String;  
begin  
  Result := Format(aFormat, [ToString]);  
end;  
 
var  
  o: TObject;  
begin  
  Writeln(o.AsString(’The object’’s name is %s’));  
end.

Remark: The helper modifier is only a modifier just after the class or record keywords. That means that the first member of a class or record cannot be named helper. A member of a class or record can be called helper, it just cannot be the first one, unless it is escaped with a &, as for all identifiers that match a keyword.