DelphiLearner
DelphiLearner

Reputation: 489

TypeCasting : what is difference between below 2 lines of code?

what is the difference between below 2 lines of code. Both are trying to get the path and one is working and other is throwing error. i am working on Delphi-7

Path:= (((FFormOwner as TForm).Designer) as IDesigner).GetPrivateDirectory; --Working
Path:= IDesigner(TForm(FFormOwner).Designer).GetPrivateDirectory ;  --Error

Below is the code which is using line of code to get the path.

constructor TsampleComponent.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FFormOwner:=TForm(Owner);
  if not (Owner is TForm) then
    repeat
      FFormOwner:=TForm(FFormOwner.Owner);
    until (FFormOwner is TForm) or (FFormOwner.Owner=nil);

  if (csDesigning in ComponentState) then
    Path:= (((FFormOwner as TForm).Designer) as IDesigner).GetPrivateDirectory
  else
    Path:=ExtractFilePath(Application.EXEName);
.
.

end;

Upvotes: 3

Views: 181

Answers (1)

David Heffernan
David Heffernan

Reputation: 613592

IDesigner(TForm(FFormOwner).Designer)

This performs a simple reinterpretation cast of Designer. It will fail because Designer is of type IDesignerHook which is not the same as IDesigner.

(FFormOwner as TForm).Designer) as IDesigner

This performs a runtime query for IDesigner and is resolved with a call to QueryInterface. This is the correct way to obtain a different interface from an existing one.

Upvotes: 9

Related Questions