AnsiString To Stream

Jhonjhon_123 picture Jhonjhon_123 · May 10, 2012 · Viewed 7.7k times · Source

I created the following code:

Function AnsiStringToStream(Const AString: AnsiString): TStream;
Begin
  Result := TStringStream.Create(AString, TEncoding.ANSI);
End;

But I'm "W1057 Implicit string cast from 'AnsiString' to 'string'"

There is something wrong with him?

Thank you.

Answer

Mason Wheeler picture Mason Wheeler · May 10, 2012

The TStringStream constructor expects a string as its parameter. When you give it an an AnsiString instead, the compiler has to insert conversion code, and the fact that you've specified the TEncoding.ANSI doesn't change that.

Try it like this instead:

Function AnsiStringToStream(Const AString: AnsiString): TStream;
Begin
  Result := TStringStream.Create(string(AString));
End;

This uses an explicit conversion, and leaves the encoding-related work up to the compiler, which already knows how to take care of it.