[Lazarus] Assigning Class to object

Kostas Michalopoulos badsectoracula at gmail.com
Mon Dec 6 10:49:38 CET 2021


On 12/6/21 02:15, R.Smith via lazarus wrote:
> Firstly the correct way of determinig class (as with your current 
> solution) is like this:
> 
>    if (MyObj is TButton) then TButton(MyObj).OnMouseDown := tmethod (not 
> important here)  else
>    if (MyObj is TPanel)  then TPanel(MyObj).OnMouseDown := tmethod (not 
> important here)  else
>    //  etc...
> 

One small detail is that the "is Thing" operator checks if the object 
belongs to the class hierarchy introduced by the Thing class, but not 
necessarily if it *is* of Thing type - it can be a subclass too. 
Sometimes this distinction is important, so in those cases instead of 
"is" you can use the ClassType property of objects (e.g. if 
MyObj.ClassType=TButton then ...).

(yeah the name of the operator is kinda optimistic in assuming Liskov 
substitution principle always applies, but in practice this is often not 
the case :-P)

In general assuming two f: TFoo and b: TBar objects with TBar being a 
subclass of TFoo, this code:

Writeln(f is TFoo, ' ', b is TFoo, ' ',
         f.ClassType=TFoo, ' ', b.ClassType=TFoo);

Will write TRUE TRUE TRUE FALSE (ie, both f and b belong to the class 
hierarchy introduced by TFoo but only f is really TFoo and b is not).

Kostas


More information about the lazarus mailing list