2
votes

This is a little different from SameText question.

I need to convert AnsiString into an Integer.

var
  param: AnsiString;
  num: Integer;
begin
  if TryStrToInt(param, num) then
  ...

In pre-Unicode Delphi I would use TryStrToInt function, but in modern Delphi there is only Unicode version of it, so I'm getting this warning: W1057 Implicit string cast from 'AnsiString' to 'string' upon call.

My question is, how to properly convert AnsiStrings in modern Delphi without getting compiler warnings (and without superfluously having to cast string to UnicodeString(text))

2
A comment for you. You are not expected to use UnicodeString in your code. Standard practise is to use its alias, string. Not that the declaration of TryStrToInt uses string rather than UnicodeString. So the explicit cast should be string(param).David Heffernan

2 Answers

7
votes

Various options are available to you:

  1. Accept and embrace Unicode. Stop using AnsiString.
  2. Use an explicit conversion to string: TryStrToInt(string(param), num).
  3. Disable warning W1057.
  4. Perform the conversion from ANSI to UTF-16 yourself with a call to MultiByteToWideChar. This isn't a serious option, but if you want to leave W1057 enabled, and not use an explicit conversion, then it's what is left.

Frankly, option 1 is to be preferred. If you try to persist the use of AnsiString through your code you will be wallowing in an endless morass of casts and warnings. If you have a need for ANSI encoded strings it is likely to be at an interop boundary. Perhaps you are reading or writing files that use ANSI encoding. Perform the conversion between ANSI and UTF-16 at the interop boundary. The rest of the time, for your internal code, use string.

0
votes

how to properly convert AnsiStrings in modern Delphi without getting compiler warnings (and without superfluously having to cast string to UnicodeString

If you don't cast from AnsiString to String, the compiler will do it for you. You can't avoid the cast. It's just a matter if you explicitly do it, or the compiler does it for you implicitly.

When you explicitly do the conversion in code (via cast), then the compiler doesn't worry about the side effects. It assumes you know what you're doing and leaves you alone.

You'll have to choose one. Compiler warning or explicit casting.

You could technically turn those compiler warnings off (but don't do this):

W1057 IMPLICIT_STRING_CAST ON Implicit string cast from ‘%s’ to ‘%s’ (Delphi)

W1058 IMPLICIT_STRING_CAST_LOSS ON Implicit string cast with potential data loss from ‘%s’ to ‘%s’ (Delphi)