0

I have two ObservableCollection objects and obj1 has attach to collection change event. Obj1 has a value from obj2 by obj1 = obj2. When I add any item on obj2 it execute collection changed event of object 1. I could not understand why this is happening.

 public MainWindow()
    {
        InitializeComponent();

        ObservableCollection<int> obj1 = new ObservableCollection<int>();
        ObservableCollection<int> obj2 = new ObservableCollection<int>();

        obj1 = obj2;

        obj1.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(obj1_CollectionChanged);

        obj2.Add(1);

}

    void obj1_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        MessageBox.Show("Testing");
    }
pchajer
  • 1,584
  • 2
  • 13
  • 25

3 Answers3

2

obj1 and obj2 refer to the same object. The code above creates two objects in memory, but the line

obj1 = obj2;

changes the reference of obj1 to the object referenced by obj2. This means that the CollectionChanged event is registered on the object which obj1 and obj2 refer to.

1

obj1 = obj2 doesn't give you a copy of obj2 in obj1. With this line you say 'obj1 please point to the same ObservableCollection as obj2'. The ObservableCollection that has been attached to obj1 before will be destroyed and both variables point to the same thing afterwards.

If you want a copy create a new ObservableCollection and fill in the other collection.

obj1 = new ObservableCollection(obj2);
Ralf
  • 1,216
  • 10
  • 20
0

You have only one ObservableCollection cause you override the reference of the variable obj1 by assign the references of obj2.

Your code:

obj1 = obj2;

Since then both variables point to the same ObservableCollection. After that assignment it is the same if you use variable obj1 or obj2 to call methods or register events on the ObservableCollection.

Jehof
  • 34,674
  • 10
  • 123
  • 155