Search code examples
delphidelphi-2007eventhandler

How to set an AnsiString param in an event handler?


I'm preparing some parts of a Delphi 2007 project to easily migrate to Delphi XE7.

I've switched a parameter's type of an event handler from string to AnsiString (This particular event handler must work with AnsiString).

Runtime package:

  TMyAnsiStringFunction = function(const APar : AnsiString) : AnsiString of object;
  TMyTestComponent = class(TComponent)
  private
    FMyAnsiStringFunction : TMyAnsiStringFunction;
  published
    property MyAnsiStringFunction : TMyAnsiStringFunction read FMyAnsiStringFunction write FMyAnsiStringFunction;
  end;

Designtime package:

procedure Register;
begin   
  RegisterComponents('MyComponents', [TMyTestComponent]);
end;

When I doubleclick on the MyAnsiStringFunction from the Object Inspector, it automatically creates a function with a string param and a string resulting type instead of AnsiString:

  TForm1 = class(TForm)
    MyTestComponent1: TMyTestComponent;
    function MyTestComponent1MyAnsiStringFunction(const APar: string): string;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

If I manually change the param and resulting type from string to AnsiString, then I get the following error while saving changes:

enter image description here

The MyTestComponent1MyAnsiStringFunction method referenced by MyTestComponent1.MyAnsiStringFunction has an incompatible parameter list. Remove the reference?

Why is this happening and is there a way to force the AnsiString type?


Solution

  • Since string is an alias for AnsiString, as far as D2007 is concerned, there is no functional difference and the IDE feels free to substitute the more commonly used string in place of the actual type used. This can be thought of as a short sight but the experiment you perform is conclusive regarding whether the AnsiString type can be forced, this is not about your code but the IDE's.

    Nothing needs to be done if only the package would be migrated. Because when compiled under XE7, the IDE cannot substitute string with AnsiString as the former is an alias for UnicodeString since D2009.

    However if consumers of the package are also to be migrated, you need to use a distinct type. Like

    type
      MyAnsiString = type AnsiString;
    

    Note that you won't be able to pass one of the types as a var parameter for the other (link) but this will probably be of no consequence when used as a parameter for an event handler.