0

I have a below code

public bool Notify(bool filterStatus)
{
   foreach (IFilterStatusListener listener in listeners)
   {
      listener.Update(filterStatus);
   }
   return true;
}

Method Update recursively calls Notify for Children

public void Update(bool status)
{
   this.isFilteredFixed = false;
   this.Notify(status);
   this.RaisePropertyChanged("IsFiltered");
}

When I run this code, I get below error enter image description here

What should I do ?

SimpleGuy
  • 2,764
  • 5
  • 28
  • 45

2 Answers2

3

When you iterate a collection with a foreach statement you can't change the collection you're iterating on, because the iterator gets lost on which position it actually is.

There are several solutions to this:

  • You iterate with a for loop
  • You create a copy of the collection you're iterating on and work on that.
Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
1

foreach expects that collection stays unchanged. You may try a normal for loop instead.

See MSDN:

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

AlexD
  • 32,156
  • 3
  • 71
  • 65