Nov 042014
 

Once in a while I run into this problem and every single time it takes me forever to remember the cause:

Say, you have got an interface and a class implementing that interface:

type
  IMyInterface = interface
    function asMyInterface: IMyInterface;
  end;

type
  TMyClass = class(TInterfacedObject, IMyInterface)
  private
    function asMyInterface: IMyInterface;
  end;

[...]

function TMyClass.asMyInterface: IMyInterface;
begin
  Result := Self as IMyInterface; // compile error here
end;

This will fail to compile in the marked line with the error “Operator not applicable to this operand type”.

The reason is simple: In order for the as operator to work on interfaces, the interface must have a GUID assigned to it. You do that in the Delphi IDE by positioning the cursor after the interface keyword and press Shift+Ctrl+G. As soon as your interface declaration looks like this …

type
  IMyInterface = interface ['{93903D10-58F7-41B0-AFB1-2A8E17F828EF}']
    function asMyInterface: IMyInterface;
  end;

… the code will compile.

(Don’t just copy this code, you will need to generate your own unique GUID as described above! Otherwise you will experience strange things.)