Search code examples
delphidelphi-xe2

Why do I get E2029 error when trying to implement a class helper for string?


We want to create a very convenient and stable conversion of data types, here string data type conversion using class helper feature in Delphi.

type
  TStringHelper = class helper for String
  public
    function AsBoolean: Boolean;
    ...
  end;

{ TStringHelper }

function TStringHelper.AsBoolean: Boolean;
begin
  Result := False;
  try
    Result := StrToBool(Self);
  except
  end;
end;

When I try to compile the above code in Delphi XE2, I get:

E2029 "declaration expected but string found"

What's the problem with my code?


Solution

  • For a string type you need to use a record helper rather than a class helper.

    type
      TStringHelper = record helper for string
        ....  
      end;
    

    Note that record helpers for fundamental data types (e.g. Integer, double, string etc.) were only introduced in XE3, so if you have an older version you are out of luck.