Vaccano
Vaccano

Reputation: 82467

Is detaching and reattching events needed when setting a BindingList

I have the following code:

    private BindingList<Box> _boxesToDisplay;
    public BindingList<Box> BoxesToDisplay
    {
        get
        {
            return _boxesToDisplay;
        }
        set 
        {
            // Unhook the old one.  Just incase
            _boxesToDisplay.AddingNew -= NewItemAdded;
            // Set the new value
            _boxesToDisplay = value;
            // Hook in the value again.
            _boxesToDisplay.AddingNew += NewItemAdded;
        }
    }

But I got to thinking. It would be best if this was an overload for the assingment operator. Then I got to wondering if they actually did that and I could just replace my code with this:

     public BindingList<Box> BoxesToDisplay { get; set; }

Is true? Would this:

     myClass.BoxesToDisplay = new BindingList<Box>();

still have the AddingNew event set to NewItemAdded() with either definition of BoxesToDisplay?

Upvotes: 1

Views: 101

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273581

Would this [...] still have the AddingNew event set to NewItemAdded() with either definition of BoxesToDisplay?

No, you are totally replacing _boxesToDisplay reference. There is no mechanism to transplant eventhandlers.

All I can say is that with the Auto-Imp property you wouldn't need the -= as much as there is no chance that something else will still have access to the old instance. But you would still have to attach to the new one.

Upvotes: 2

Related Questions