Advertisement
Guest User

Proof that cloning a dictionary with MemberwiseClone is bad...

a guest
Oct 15th, 2010
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.47 KB | None | 0 0
  1. void Main()
  2. {
  3.     var original = new BadDict<string, int> { { "a", 1 } };
  4.     var clone = original.Clone();
  5.     Console.WriteLine (clone["a"]); // 1, OK
  6.     Console.WriteLine (original["a"]); // 1, OK
  7.    
  8.     clone["a"] = 42;
  9.     Console.WriteLine (clone["a"]); // 42, OK
  10.     Console.WriteLine (original["a"]); // 42, oops !
  11.    
  12. }
  13.  
  14. class BadDict<K,V> : Dictionary<K,V>
  15. {
  16.     public BadDict<K,V> Clone()
  17.     {
  18.         return (BadDict<K,V>)MemberwiseClone();
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement