Stregor
Stregor

Reputation: 21

Delphi - interface as another interface

I have two interfaces, ISomeInterfaceRO (read only) and ISomeInterface.

ISomeInterfaceRO = interface(IInterface) ['{B28A9FB0-841F-423D-89AF-E092FE04433F}']
function GetTest: Integer;
  property Test : integer read GetTest;
end;

ISomeInterface = interface(ISomeInterfaceRO) ['{C7148E40-568B-4496-B923-89BB891A7310}']
    procedure SetTest(const aValue: Integer);
    property Test : integer read GetTest write SetTest;
end;

TSomeClass = class(TInterfacedObject, ISomeInterfaceRO, ISomeInterface)
private
    fTest: integer;
protected
  function GetTest: integer;
  procedure SetTest(const aValue: integer);
public
  property Test: integer read GetTest write SetTest;
end;

function TSomeClass.GetTest: integer;
begin
  Result := fTest;
end;

procedure TSomeClass.SetTest(const aValue: integer);
begin
  fTest := aValue;
end;

Then, i use read only interface except one place, when i create TSomeClass instance as ISomeInterface and fill it. example:

Function GetSome: ISomeInterfaceRO;
var
  SomeInterface: ISomeInterface;
begin
  SomeInterface := TSomeClass.Create;
  SomeInterface.Test := 10;
  result := SomeInterface as ISomeInterfaceRO;
end;

My question is: that "result := SomeInterface as ISomeInterfaceRO;" is a safe and recommended construction? Or is a another way to do this? I debugged that code, and compiler properly decreased reference count to ISomeInterface and increased to ISomeInterfaceRO when i use "as".

Upvotes: 1

Views: 295

Answers (1)

Stefan Glienke
Stefan Glienke

Reputation: 21758

Result := SomeInterface as ISomeInterfaceRO;

is safe but not necessary at all because ISomeInterface inherits from ISomeInterfaceRO and thus SomeInterface is assignment compatible to Result. That means you can just write

Result := SomeInterface;

I however would put a constructor on TSomeClass that takes the value so you can directly write:

Result := TSomeClass.Create(10);

Upvotes: 4

Related Questions