Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NotifyCollectionChangedEventArgs has NewItems and OldItems as plural?

Tags:

c#

.net

generics

I'm new to C# and OOP, just a question on NotifyCollectionChangedEventArgs. I don't understand why it has NewItems and OldItems rather than NewItem and OldItem. For example, we use ObservableCollection as:

ObservableCollection<Person> people = new ObservableCollection<Person>()
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;

static void people_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.Action == NotifyCollectionChangedAction.Add)
   {
     foreach (Person p in e.NewItems)
     {
        Console.WriteLine(p.ToString());
     }
   }

}

so each time we add a new Person in the collection as:

people.Add(new Person("John", "Smith", 32));

CollectionChanged trigger people_CollectionChanged, so e.NewItems will only contain one person (the one I just added), so what's the point to assume e.NewItems could have more than one item as it always can only have one item?


2 Answers

The event you're subscribing to is actually defined by the INotifyCollectionChanged interface, and implemented by ObservableCollection.

While ObservableCollection doesn't have methods for adding multiple items at once, it does have a ClearItems method, which could remove multiple items at once. That's one reason I can think of for having plural names, since they could contain more than one item.

Also, since it's an interface, it could be implemented by other classes that do implement something like AddRange or RemoveWhere, etc. methods, which would again raise this event with multiple items.

like image 113
DiplomacyNotWar Avatar answered Sep 03 '25 07:09

DiplomacyNotWar


If you look at the official documentation, you will notice that the backing entity is an IList implementation. Given that it's a list, it's only natural that the property name is in plural.

For example, if I use AddRange, multiple items will be added at once, and NewItems (or OldItems, if you removed content) would be populated with more than one entry.

like image 41
Den Delimarsky Avatar answered Sep 03 '25 05:09

Den Delimarsky