Modifying collection while enumerating

46 views
Skip to first unread message

Glienke, Stefan

unread,
Feb 12, 2013, 5:16:10 AM2/12/13
to spri...@googlegroups.com

Currently the collections have the bug that modifying them while enumerating results in wrong data or endless loops.

See this example:

 

var

  l: IList<Integer>;

  i: Integer;

begin

  l := TCollections.CreateList<Integer>;

  l.AddRange([1, 2, 3]);

  l.RemoveRange(l); // <- this will skip every 2nd item

  for i in l do

    Writeln(i);

 

  l.Clear;

  l.AddRange([1, 2, 3]);

  l.AddRange(l); // <- infinite loop

  for i in l do

    Writeln(i);

end.

 

The solution I chose in DSharp is the same as in .Net where every list contains a version that gets increased every time the list is modified.

An enumerator remembers the version of the list when it was created and raises an exception when the list gets modified during the enumeration.

 

I suggest implementing that into the next refactored version of the spring collections.

 

Another thing is the IsReadOnly property which should be considered in the methods that modify the list and raise an exception if it is true which currently does not happen.

Reply all
Reply to author
Forward
0 new messages