0

I have the next problem.

I have a type, like Fooo : List, and I fill this collection from XAML. Is it possible to override "add" methods at List<> (Add, AddRange, Insert, etc) in Fooo, in order to implement some "add logic" (e.g. if item with some property exist - throw exception)? I'm trying to redefine "add" methods at List (using "new" keyword, but it doesn't work).

Any ideas?

slavka
  • 119
  • 6
  • It's not clear what you're asking. As noted below, you can't override the methods. The best you can do is _hide_ the `Add()` method by using `new` in the method declaration. But code that doesn't view the object as your `Fooo` type won't get the method; it's generally bad to hide members (which is why C# forces you to be explicit when you do). It's not clear why you want to override the adding process; you can implement `IList` yourself instead of inheriting `List`, but why not just not add wrong elements in the first place. What's the actual scenario here? See [mcve] and [ask]. – Peter Duniho Aug 21 '16 at 19:15

1 Answers1

0

Is it possible to override "add" methods at List<> (Add, AddRange, Insert, etc) in Fooo

No, you can't. We should encapsulate List<T> and implement IList<T>

There are some questions talking about this:

Community
  • 1
  • 1
Franklin Chen - MSFT
  • 4,845
  • 2
  • 17
  • 28
  • Ok, if I have implemented Fooo, XAML must invoke methods to add items from Fooo, not List<>, right? Correct me, if I am wrong. – slavka Aug 21 '16 at 17:03
  • @slavka In xaml, you should fill the List and it will call Add method to append new item to the list. Implementing the List interface is the right way – Franklin Chen - MSFT Aug 21 '16 at 17:10