knightmare313
knightmare313

Reputation: 95

Exception : Collection was modified; enumeration operation may not execute, thrown while clone()

I'm trying to write a info provider class. I want to provide deep copy through Clone(). So what I tried is:

public MyInfoClass Clone()
{
     MyInfoClass temp = (MyInfoClass)this.MemberwiseClone();
     foreach (MySystem sys in _mySystems)
     {
         temp.AddSys(sys);
     }
     return temp;
}

The collection is as follows. Whenever the collection has at least a object it throws the exception:

Collection was modified; enumeration operation may not execute.

private ObservableCollection<MySystem> _mySystems;

public ObservableCollection<MySystem> MySystems
{
    get{ return _mySystems; }
}

I tried debugging and observed that temp.AddSys(sys) executes successfully but on the next step the exception is thrown. Can you please help?

Upvotes: 1

Views: 696

Answers (1)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

this.MemberwiseClone() makes a shallow copy of the members and for reference types both objects have the same reference so you are essentially enumerating and modifying the same collection. You need to create a new collection and add the items to it.

 MyInfoClass temp = (MyInfoClass)this.MemberwiseClone();
 temp._mySystems = new ObservableCollection<MySystems>();

 foreach (MySystem sys in _mySystems)
 {
     temp.AddSys(sys);
 }

 return temp;

Upvotes: 2

Related Questions