3

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?

WΩLLE - ˈvɔlə
  • 6,404
  • 6
  • 44
  • 70

1 Answers1

1

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.

Evk
  • 84,454
  • 8
  • 110
  • 160
  • In my use-case, it is just necessary to process new and old items. Moving does not matter. If you trigger e.g. the `replace` action, i am processing the old an the new item with my simplified code as well. – WΩLLE - ˈvɔlə Oct 10 '17 at 16:00
  • 1
    @Wolle You say moving does not matter, but you code will first execute addAction and then removeAction for moved element, I doubt that is what you intend to do in this case (you prefer to ignore it if it really does not matter). – Evk Oct 10 '17 at 16:05