Delphi XE2:

Delphi XE2:

function TSomeClass.AddHotkey(const _Caption: string): string;
var
i: Integer;
c: AnsiChar;
begin
Result := _Caption;
if HotKey = #0 then
Exit; //==>
c := UpCase(HotKey);
for i := 1 to Length(Result) do
if UpCase(Result[i]) = c then begin
Insert('&', Result, i);
Exit; //==>
end;
Result := Result + ' (&' + c + ')';
end;

Error: "Operator not applicable to this operand type" in the line

if UpCase(Result[i]) = c then begin

WTF?
(Hotkey is a property of type AnsiChar.)

Typecasting c to Char makes this compile:

if UpCase(Result[i]) = Char(c) then begin

And then there is a warning:

"Implicit string cast from AnisChar to string" in the line

Result := Result + ' (&' + c + ')';

which again can be "fixed" with a cast from c to Char.

Can somebody please explain to me, why an implicit typecast from AnsiChar to Char could possibly become a problem?

Comments

  1. Actually the implicit cast cannot become a problem. That's why there is another similar warning with the extension "with possible data loss" for the reverse case. The warning is just a hint for you that this implicit cast happens. It has no influence to the program nor does it indicate any harm. If you don't want it to be emitted, you can disable that specific warning in the project options.

    ReplyDelete
  2. Uwe Raabe although, a string is a glorified array of Char... so it would be better to use the correct type in the first place (Char when enumerating a string, AnsiChar when enumerating an AnsiString).

    ReplyDelete
  3. Chris Rolliston Agreed! The real question should be, why HotKey has to be an AnsiChar in the first place. Especially as it is a property it should be easy to wrap the access in the Getter and Setter in case the inner representation is one byte wide. This would avoid all those errors and warnings later in the code.

    ReplyDelete
  4. Why not just use the below and take one hint for granted:

    var
    c: Char;

    ReplyDelete
  5. Jeroen Wiert Pluimers I had already done exactly that (after posting this question), but I don't want any hints in the code (hints are warnings and warnings are potential errors), so in addition I added a type cast in c := Char(Hotkey);

    ReplyDelete
  6. HotKey is declared AnsiChar because I want to make it clear that unicode characters are not allowed in this case. That's of course still not fool proof, since depending on the charset, an AnsiChar might still be one of the undesired characters.

    ReplyDelete

Post a Comment