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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With