Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use "is" to check or an exact class (not a descendant)?

Tags:

delphi

TBase = class(TObject)
...

TDerived = class(Tbase)
...

if myObject is TBase then ...

can I code this somehow and have it return false if myObject is of class TDerived?

like image 683
Mawg says reinstate Monica Avatar asked Nov 26 '25 16:11

Mawg says reinstate Monica


2 Answers

If you need exact class type check use ClassType method:

type

TBase = class(TObject)
end;

TDerived = class(Tbase)
end;

procedure TForm1.Button1Click(Sender: TObject);
var
 A: TBase;

begin
  A:= TBase.Create;
  if A.ClassType = TBase then ShowMessage('TBase');  // shown
  A.Free;
  A:= TDerived.Create;
  if A.ClassType = TBase then ShowMessage('TBase again'); // not shown
  A.Free;
end;
like image 70
kludg Avatar answered Nov 30 '25 17:11

kludg


You can use ClassType method, or just check PPointer(aObject)^=aClassType.

begin
  A:= TBase.Create;
  if A.ClassType = TBase then ShowMessage('TBase');  // shown
  if PPointer(A)^ = TBase then ShowMessage('TBase');  // shown
  A.Free;
  A:= TDerived.Create;
  if PPointer(A)^ = TBase then ShowMessage('TBase again'); // not shown
  if A.ClassType = TBase then ShowMessage('TBase again');  // not shown
  A.Free;
end;

If your code is inside a class method, you can use self to get the class value:

class function TBase.IsDerivedClass: boolean;
begin
  result := self=TDerivedClass;
end;
like image 23
A.Bouchez Avatar answered Nov 30 '25 16:11

A.Bouchez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!