Delphi provided Runtime Type Information (RTTI) more than a decade ago. Yet even today many developers aren't fully aware of its risks and benefits. This article provides an overview of the RTTI usage in Delphi for Win32.
In short, Runtime Type Information is information about an object's data type that is set into memory at run-time.
You are probably using this powerful but unfortunately inadequately documented feature of Delphi in your every day projects.
RTTI provides a way to determine if an object's type is that of a particular class or one of its descendants. The is and as operators commonly used in Delphi language, rely on the presence of some form of RTTI. The is operator, which performs dynamic type checking, is used to verify the actual runtime class of an object. The as operator performs checked typecasts.
In Delphi 7 (and 2005) the typinfo unit defines type, classes and objects you use when working with the RTTI.
RTTI in Delphi - ExplainedThe "Run-Time Type Information In Delphi - Can It Do Anything For You?" article by Brian Long provides a great introduction to the RTTI capabilities of Delphi. Brian explains that the RTTI support in Delphi has been added first and foremost to allow the design-time environment to do its job, but that developers can also take advantage of it to achieve certain code simplifications.
This article also provides a great overview of the RTTI classes along with a few examples. Examples include: Reading and writing arbitrary properties, common properties with no common ancestor, copying properties from one component to another, etc.
RTTI in Delphi - An ExampleHere's a small example of the powers of the RTTI. This example shows how to obtain the ancestry of a component using the ClassType and ClassParent properties. It uses a button and a list box on a form. When the user clicks the button, the name of the button’s class and the names of its parent classes are added to the list box (found in the Delphi Help).
procedure TForm1.Button1Click(Sender: TObject) ;
ClassRef := Sender.ClassType;
while ClassRef <> nil do
ClassRef := ClassRef.ClassParent;
The list box contains the following strings after the user clicks the button:
RTTI in Delphi - More Examples
- Get Enum Information using RTTI
- Generic Solution to Coloring the Focused Data Entry Delphi Control
- How to execute a method (procedure/function) by name
- Converting between enumerated type values and strings
- How to set the DataSource property to several db-aware controls in one call
- Get the list of events with attached event handlers
- How to to write to a read-only property