4

If I create a new ObservableCollection<T>, and a CollectionChanged listener as follows:

var c = new ObservableCollection<MyType>();
c.CollectionChanged += new NotifyCollectionChangedEventHandler(h);
...
void h(object sender, NotifyCollectionChangedEventArgs e) 
{
    IList newItems = e.NewItems;
    // non generic IList!  :(
}

Why isn't e.NewItems an IList<MyType>?

funkybro
  • 8,432
  • 6
  • 39
  • 52

2 Answers2

5

The ObservableCollection is designed to support databinding scenarios in platforms like WPF where the databound controls don't care about the type of the collection they're bound to. Making the notifications generic would only make it much harder to write the controls without giving any benefit.

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • Hmm. This seems to suggest that if I need to manually write my own `NotifyCollectionChangedEventHandler`s, I'm Doing It Wrong™. – funkybro Nov 03 '11 at 15:24
  • No, I wouldn't say that you're Doing It Wrong; just that the cost-benefit analysis doesn't support having a generic version. Creating your own handlers is a perfectly valid thing to do, but rare enough that it isn't worthwhile adding special support in the platform for a generic version. – Gabe Nov 03 '11 at 15:27
  • 1
    Given that you just need to put a `.Cast()` or `.OfType()` on the `NewItems` property to get your generic list, I'd definitely say that it isn't worthwhile writing your own – Steve Greatrex Nov 03 '11 at 15:39
  • Yeah, got a fairly complex viewmodel going on in my app... My VM is a class (implementing `INotifyPropertyChanged`) containing an `ObservableCollection` of "sub" VMs, each of which also implements `INotifyPropertyChanged`. I need to listen for a change to any item within the collection, to trigger `PropertyChanged` on a property in the base class. Maybe this needs its own question! – funkybro Nov 03 '11 at 15:45
1

Presumably so that it can be used for non-generic collections as well as ObservableCollection<T>

Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73