[C#] Why is ReadOnlyObservableCollection.CollectionChanged not public?


Answers

I've found a way for you of how to do this:

ObservableCollection<string> obsCollection = new ObservableCollection<string>();
INotifyCollectionChanged collection = new ReadOnlyObservableCollection<string>(obsCollection);
collection.CollectionChanged += new NotifyCollectionChangedEventHandler(collection_CollectionChanged);

You just need to refer to your collection explicitly by INotifyCollectionChanged interface.

Question

Why is ReadOnlyObservableCollection.CollectionChanged protected and not public (as the corresponding ObservableCollection.CollectionChanged is)?

What is the use of a collection implementing INotifyCollectionChanged if I can't access the CollectionChanged event?




There are definitely good reasons for wanting to subscribe to collection changed notifications on a ReadOnlyObservableCollection. So, as an alternative to merely casting your collection as INotifyCollectionChanged, if you happen to be subclassing ReadOnlyObservableCollection, then the following provides a more syntactically convenient way to access the a CollectionChanged event:

    public class ReadOnlyObservableCollectionWithCollectionChangeNotifications<T> : ReadOnlyObservableCollection<T>
{
    public ReadOnlyObservableCollectionWithCollectionChangeNotifications(ObservableCollection<T> list)
        : base(list)
    {
    }

    event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged2
    {
        add { CollectionChanged += value; }
        remove { CollectionChanged -= value; }
    }
}

This has worked well for me before.




How can I implement an interface member in protected?

If you closely examing ReadOnlyObservableCollection you will see that it explicitly implements INotifyPropertyChanged. In other words, the protected event handler is not the real implementation of the interface - INotifyCollectionChanged.CollectionChanged is.




I am agree with Mark Seemann's answer and also take a look on this question some useful stuff can be found in answers. Its all due to explicit interface implementation. Try to implement INotifyPropertyChanged (or any other interface) explixetly in your type and then open it through Object Browser, you will see that is shows interface memeber even as private.