Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to check NotifyCollectionChangedAction in a CollectionChanged event?

I wonder if it is necessary to check the NotifyCollectionChangedAction enum of the NotifyCollectionChangedEventArgs, when subscribing to the CollectionChanged event. Every example I stumbled upon does it like this:

myCollection.CollectionChanged += (sender, eventArgs) =>
{
    if (eventArgs.Action == NotifyCollectionChangedAction.Add)
    {
        foreach (SampleClass sampleObject in eventArgs.NewItems)
        {
            addAction(sampleObject);
        }
    }
    else if (eventArgs.Action == NotifyCollectionChangedAction.Remove)
    {
        foreach (SampleClass sampleObject in eventArgs.OldItems)
        {
            removeAction(sampleObject);
        }
    }
    // ...
};

Is it possible to ignore the NotifyCollectionChangedAction and just simplify the code like this:

myCollection.CollectionChanged += (sender, eventArgs) =>
{
    eventArgs.NewItems?.OfType<SampleClass>()
        .ToList()
        .ForEach(addAction);

    eventArgs.OldItems?.OfType<SampleClass>()
        .ToList()
        .ForEach(removeAction);
};

What are the downsides of this idea? Is there anything I have missed?

like image 251
ˈvɔlə Avatar asked Nov 21 '25 16:11

ˈvɔlə


1 Answers

It depends on what you are trying to do, because those code samples are not equivalent. There are more action types than just Add and Remove. For example there is Replace action. If I do this:

myCollection[0] = new MyObject();

CollectionChanged will be fired with action type Replace, OldItems will contain replaced item (old myCollection[0]) and NewItems will contain new MyObject() item. First code sample will completely ignore this event. Second code sample will handle both items with addAction and removeAction. If you do:

myCollection.Move(0,1);

It will fire event with action Move where both OldItems and NewItems will contain moved item. First sample again will ignore it and second will perform addAction and removeAction on the same item being moved, which might lead to surprising results I guess.

like image 65
Evk Avatar answered Nov 24 '25 06:11

Evk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!