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?
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?
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;
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;