Delphi Prism: DelphiString

Was just reading the source code for ShineOn (the RTL implementation in Delphi Prism) and found an interesting piece: DelphiString (in /ShineOn.RTL/DelphiString.pas).

What is it? It is a class that tries to replicate the behavior of the Win32 Delphi’s String type.The difference between Delphi’s String and .NET string is that the first one is mutable (aka can be written to but not thread-safe) and the second is immutable (can’t be modified making it thread-safe but harder to use).

If you are porting an application over Win32 Delphi you can’t normally use .NET’s String class because most of your code surely makes operations on strings.

Back to DelphiString; you might be tempted to use it simply by replacing all instances of String with DelphiString in your code — WRONG! Because Win32 Delphi uses a technique called Copy-On-Write, code like this:

S1 := 'John'
S2 := S1;
S2[1] := '_';
ASSERT((S1= 'John') and (S2 = '_ohn'));

… will work as expected (in Win32 Delphi) even if S2 is initially pointing to the same string as S1! In Delphi Prism, S2 will point to the same object as S2, but no “copy-on-write” will be performed and both strings will eventually be changed to “_ohn”. A simple “replace all String with DelphiString” will not be enough. I would kindly suggest that the application gets ported to use .NET String class rather than DelphiString.