Mirror

Testing if two objects are "related" or "identical" (RTTI) (Views: 101)


Problem/Question/Abstract:

Testing if two objects are "related" or "identical" (RTTI)

Answer:

Do you need to know whether object a is of a derived class from the class that another object b is of? Or if they may even be of the same class?

The following little code snippet tells it..


program dummy;

var
  a, b: TObject;

begin
  // some code to assign the pointers
  // ...

  // now evaluate the RTTI of two instantiated objects
  if a is b then
    ShowMessage('a is derived from b or same class');

  if a.classtype = b.classtype then
    ShowMessage('a and b are of the same class');

  // alternative to ClassType comparison (slower!)
  if a.ClassName = b.ClassName then
    ShowMessage('a and b are of the same class')
end.

<< Back to main page