1

I want to override Add(MyType t) for a class derived from ObservableCollection<MyType>. However I cannot override Add. Why?

I therefore added AddIem(MyType t)and use that function instead, which works fine. But I want to prevent someone erroneously using Add so I implemented Add (throwing an exception). But that doesn't hide the Add method of the ObservableCollection. Any idea why and how I could achieve my goal?

Johannes Schacht
  • 930
  • 1
  • 11
  • 28
  • Possible duplicate [StackOverflow](http://stackoverflow.com/a/2176263/579895) – Pikoh Jun 25 '16 at 10:45
  • 1
    a 5 seconds google search led me to the following answer: https://channel9.msdn.com/Forums/TechOff/555226-Is-it-possible-to-override-ObservableCollectionTAdd – A.B. Jun 25 '16 at 10:47
  • Related read: http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt – Caramiriel Jun 25 '16 at 11:29

1 Answers1

1

Keep your ObservableCollection private, and expose the items with a public ReadOnlyObservableCollection which reflects the items in the private collection.

If you need to expose a specialized AddItem method to other classes, you could make it a member of your viewmodel class, or you could subclass ReadOnlyObservableCollection and put it there. Call it MostlyReadOnlyObservableCollection.