Search code examples
delphidelphi-11-alexandria

Helper Record not validated on compile


Using Delphi 11.3 (including Patch 1).

I created a Record Helper for a custom Variant type.

My helper record is working, but the compiler doesn't validate my helper call on compile.

Type
  TTest = Type Variant;

  TTestHelper = Record Helper for TTest
  Public
    Function GetV: Variant;
    Function AsString: String;
  end;

{ TTestHelper }

function TTestHelper.GetV: Variant;
begin
  Result := Self;
end;

function TTestHelper.AsString: String;
begin
  Result := VarToStr(Self);
end;


//Simple button clik
procedure TForm5.Button1Click(Sender: TObject);
var
  V: TTest;
begin
  V := 'test';
  V := V.GetV; //Works as intended
  
  V := V.fopergkergprgkergtk4k3tp3gkg3p; //Compiles without any issue, but of course it gives an "Invalid Variant Operation" when I press the button.
end;

How can it be that the compiler compiles code that is obviously rubbish, and why is my Code Completion window not showing any of my methods (GetV and AsString)?


Solution

  • How can it be that the compiler compiles code that is obviously rubbish

    That is a feature of Variant.

    A Variant can contain different things, including an IDispatch interface to a COM object that "late-binds" to functions/properties at runtime instead of at compile-time. A COM object might provide a function fopergkergprgkergtk4k3tp3gkg3p that may only be detectable at runtime, so the compiler allows everything after . on a Variant to compile, and it will be resolved at runtime, so it might succeed or fail at runtime.