2

I've got a List of objects which have a method that's being ran. Some objects' method remove other objects from the list, which causes an InvalidOperationException.

The code somewhat (simplified) looks like this:

static List<myObject> olist = new List<myObject>();
// fill list
foreach (myObject obj in olist) {
    obj.func();
}

A func() of an obj may contain something like this:

olist.Remove(specificListItem);

Which obviously causes the exception above. Right now, the current setup of having a foreach run the objects' own methods have to stay - what workaround would be the best here?

Since we're running a method of undetermined (at the time of beginning the foreach) function - inside of an object, we can't use tricks live reversing the order mentioned here.

Community
  • 1
  • 1
Exec
  • 407
  • 6
  • 18
  • How does the object know what list it's in? – D Stanley Aug 18 '16 at 00:50
  • It's a static list; fixed in question. – Exec Aug 18 '16 at 01:02
  • Both of those (static field and object knowing about its container) are code smells. I would suggest redesigning your process to clean those up; if you aren't interested in that a `for` loop is the next best option. – D Stanley Aug 18 '16 at 01:19

0 Answers0