0

I have a property in a third-party library that is a List<T>, and I want to be notified when the list changes. Is there any way to achieve this without modifying the code of the third-party library?

public sealed class ThirdPartyObject
{
    public List<string> Names { get; } = new List<string>();
}

In other words, I need a mechanism that will allow my client code to be notified when the List<T> changes, so that I can take appropriate action.

I tried something like this, but it did not work:

var col = new ObservableCollection<string>(myObj.Names);
col.CollectionChanged += (sender, args) =>
{
    // notify
};
Vahid
  • 5,144
  • 13
  • 70
  • 146

1 Answers1

1

If the library does not have any event or callback you cannot get a notification straight away.

You could perhaps modify the library by dissemble it and recompiling. But this will possibly violate the license agreement with the library author if there is any. It might also be possible to do at runtime, but I would recommend against both alternatives since it will make it likely to break if a new version of the library is released.

A workaround would be to use polling. Create a timer of you choice that periodically compares the current list with a saved copy (keep thread safety in mind when doing this), raises an event for any items that are different, and creates a new copy of the list. Using a poller will mean that events are not raised when they happen, and it will use some resources to compare the lists even if no changes has been made. On the other hand, if frequent changes occur, it might be better to raise a few infrequent events rather than for each change.

If you are not care about duplicates or ordering you can use a hashSet to compare two lists:

        var newItems = newList.ToHashSet();
        var removedItems = oldList.ToHashSet();
        var intersection = newItems.ToHashSet();
        intersection.IntersectWith(removedItems);
        removedItems.ExceptWith(intersection);
        newItems.ExceptWith(intersection);
JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Thanks Jonas, Actually this is the method I am currently using as a last resort, but you ever wonder if there is a more elegant way! – Vahid Mar 10 '21 at 09:47
  • @Vahid, the best way would probably be to petition the library author to make a change. Providing good arguments for the change or offering money often helps. Or do it yourself and submit a pull request if it is an open source project. – JonasH Mar 10 '21 at 09:54