.NET Extension Events

I want to add events to some built in .NET classes. For example, I want to add the following events to the general List(T)

:

  • ItemAdded
  • ItemRemoved
  • ListChanged
  • etc.

I can think of several ways to do this, but I'm not sure which approach is best.

  • I could use "extension events", that is, if there is such a thing or a way to use extension methods to simulate event-like functionality.
  • I could inherit from List(T)

    and override the required methods and properties.
  • I could inherit from List(T)

    and shadow the required methods and properties.
  • I could create a new class that implements IList(T)

    and then completes the rest of the functionality List(T)

    that is missing IList(T)

    .

Obviously option 4 is the biggest job, which is not a big problem if I only wanted to extend one class. However, I also want to avoid unpleasant side effects.

What are the advantages, disadvantages, and caveats for each approach?

Note. I really don't know much about IList (T). I also want to add "extenstion events" to other classes.

+2


source to share


2 answers


  • There is no such thing as "extension events", and you cannot use extension methods to simulate this: extension events cannot add state to existing classes, which is what you want.

  • I think you mean overriding, not overloading. This will work, it's a little clunky - and means you can't use the normal one ToList

    from LINQ, etc., because then you just get List<T>

    .

  • Shading is more annoying than overriding. This means that events may or may not be raised depending on how the caller calls the method. Ik.

  • This would be preferred and you could add an extension method List<T>

    to wrap it. One drawback is that if anyone else "knows" about the expanded collection, you will not notice changes made this way.



Have you looked ObservableCollection<T>

? Please note that this will be copied from the list if you provide it in the constructor rather than wrapping the list.

+6


source


"extension events" do not exist, do not have extension properties, or anything other than extension methods. Personally, I would like to see extension properties (given that they are just wrappers for functions), but I'm not sure how you could implement static style extension events that require extension.



There is nothing to prevent you from adding these events to the class itself. However, you may have more success looking at BindingList<T>

as it is more in line with the monitoring activity you seem to want to do.

+2


source







All Articles