Reputation: 40149
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?
Upvotes: 2
Views: 3638
Reputation: 468
Better way;
type
TBase = class(TObject)
end;
TDerived = class(Tbase)
end;
procedure TForm1.Button1Click(Sender: TObject);
var
A, B: TObject;
begin
A:= TBase.Create;
if A.ClassType = TBase then ShowMessage('A is Exacly TBase'); // shown
if A is TBase then ShowMessage('A is TBase or SubClass of TBase'); // shown
if A is TDerived then ShowMessage('A is TDerived or SubClass of TDerived '); // NOT shown!!
A.Free;
B:= TDerived.Create;
if B.ClassType = TBase then ShowMessage('TBase again'); // not shown
if B is TBase then ShowMessage('B is TBase or SubClass of TBase'); // shown
if B is TDerived then ShowMessage('B is TDerived or SubClass of TDerived '); // shown!!
B.Free;
end;
Upvotes: 1
Reputation: 411
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;
Upvotes: 2
Reputation: 27493
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;
Upvotes: 16