1

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?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
knightmare313
  • 95
  • 2
  • 9
  • I don't see where MySystems is being used. But, seems like, somwhere, you are enumerating over a collection and trying change that collection while doing so! Like foreach(var item in items) { items.Remove(someItem); } – Arghya C Sep 12 '15 at 07:38
  • 1
    Side note - `MemberwiseClone` is for shallow copies, not deep copies. If you want deep clone, see [this](http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically) – Yuval Itzchakov Sep 12 '15 at 08:07

1 Answers1

2

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;
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61