Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Delphi warn when assigning ShortString to string?

Tags:

I'm converting some legacy code to Delphi 2010.

There are a fair number of old ShortStrings, like string[25]

Why does the assignment below:

type 
  S: String;
  ShortS: String[25];

...
S := ShortS;

cause the compiler to generate this warning:

W1057 Implicit string cast from 'ShortString' to 'string'.

There's no data loss that is occurring here. In what circumstances would this warning be helpful information to me?

Thanks!

Tomw

like image 401
RobertFrank Avatar asked Jan 22 '10 23:01

RobertFrank


2 Answers

It's because your code is implicitly converting a single-byte character string to a UnicodeString. It's warning you in case you might have overlooked it, since that can cause problems if you do it by mistake.

To make it go away, use an explicit conversion:

S := string(ShortS);
like image 117
Mason Wheeler Avatar answered Oct 07 '22 18:10

Mason Wheeler


The ShortString type has not changed. It continues to be, in effect, an array of AnsiChar.

By assigning it to a string type, you are taking what is a group of AnsiChars (one byte) and putting it into a group of WideChars (two bytes). The compiler can do that just fine, and is smart enough not to lose data, but the warning is there to let you know that such a conversion has taken place.

like image 35
Nick Hodges Avatar answered Oct 07 '22 20:10

Nick Hodges