Search code examples
delphicastingwarningsdelphi-12-athens

Cast Shortstring to string


Good afternoon.

I'm reviewing an old code and it has things like this everywhere: var1 : string[10] or var2 : string[5]...the length of the string is mandatory, it can't be longer.

But then I have to use all these variables and form a string and a cast is made like this: string(var1) + string(var2)...and the compiler shows a warning

Explicit string cast from 'ShortString' to 'string'

I need to get rid of those warnings. Would it be possible to declare those variables in a different way or a different cast?


Solution

  • A ShortString is a fixed-length string using AnsiChar characters, but (Unicode)string is a variable-length string using WideChar characters. Casting between them, whether implicitly or explicitly, can potentially lose/destroy your character data, hence why the warnings exist.

    The best option would be to just use string everywhere. But, if you absolutely need to use ShortString then you can get rid of the W1059 warning by changing the explicit cast to use AnsiString instead of string, as that will be a loss-less cast:

    AnsiString(var1) + AnsiString(var2)

    Just know that if you later assign that result to a string without casting, you will get a W1057 warning:

    W1057 Implicit string cast from 'AnsiString' to 'string'

    And if you explicitly cast it to string instead, you will be back to the W1059 warning:

    W1059 Explicit string cast from 'AnsiString' to 'string'

    To avoid these warnings, you would have to turn them off in the Project Options, or use {$WARN EXPLICIT_STRING_CAST OFF|DEFAULT} and {$WARN IMPLICIT_STRING_CAST OFF|DEFAULT} directives around any code you review as being ok for your needs.

    Alternatively, you might consider changing your ShortString variables to byte[] arrays and then use TEncoding.GetString() when you need to convert them to string values.