TStringList oddity

I’ve been using Delphi since 1995, so I’ve used TStringList a few thousand times over the years. You would think that means I know it inside out - but today I discovered this gem while trying to figure out how items were magically disappearing

procedure TStrings.SetValueFromIndex(Index: Integer; const Value: string);
begin
  if Value <> '' then
  begin
    if Index < 0 then Index := Add('');
    Put(Index, Names[Index] + NameValueSeparator + Value);
  end
  else
    if Index >= 0 then Delete(Index); //<<<< WTF???
end;

So it seems you cannot use .ValueFromIndex to set a value to an empty string as it Deletes the item.

I’m struggling to figure the mindset of whoever decided that was a good idea :roll_eyes:

I’ve probably encountered this issue before and forgotten about it… posting here so I get a search result next time I search for ValueFromIndex :smirk:

1 Like

Yep, been there, saw that, have bitemarks :wink:

Alex

``


So it seems you cannot use .ValueFromIndex to set a value to an empty string as it Deletes the item.

Why would you not use
Strings[index]:=’’;
or as it is the default
MyStringList[Index]:=’’;

Using SetValueFromIndex risks breaking a sorted list as it is not virtual.

Because I’m using it for Name=Value pairs

String.ValueFromIndex[index] := 'foo'; 

sets the value without changing tne name.

And the Put in the implementation does any sorted required,
Sorry

IIRC, the ‘mindset’ was to imitate Win32 .ini routines, which delete entries (and even whole sections!) by setting the value to an empty string. See WritePrivateProfileStringA function (winbase.h) - Win32 apps | Microsoft Docs.