1

I need to identify if a list is updated (item added/removed). I need to use System.Collections.Generic.List<T>, I cannot use ObservableCollection for this (and subscribe to it's CollectionChanged event).

Here is what I have tried so far:

I am using Fody.PropertyChanged instead of implementing INotifyPropertyChangedEvent - Fody Property Changed on GitHub

[AlsoNotifyFor("ListCounter")]
public List<MyClass> MyProperty
{get;set;}

public int ListCounter {get {return MyProperty.Count;}}

//This method will be invoked when ListCounter value is changed
private void OnListCounterChanged()
{
   //Some opertaion here
}

Is there any better approach. Please let me know if I am doing something wrong, so that I can improve.

sampathsris
  • 21,564
  • 12
  • 71
  • 98
Nikhil Chavan
  • 1,685
  • 2
  • 20
  • 34

1 Answers1

2

You can use extension methods:

    var items = new List<int>();
    const int item = 3;
    Console.WriteLine(
        items.AddEvent(
            item,
            () => Console.WriteLine("Before add"),
            () => Console.WriteLine("After add")
        )
        ? "Item was added successfully"
        : "Failed to add item");

Extension method itself.

public static class Extensions
{
    public static bool AddEvent<T>(this List<T> items, T item, Action pre, Action post)
    {
        try
        {
            pre();
            items.Add(item);
            post();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}
Margus
  • 19,694
  • 14
  • 55
  • 103
  • Note that I assume you would use "AddEvent" instead "Add" wherever you need to track add event. You did not mention if event should be thrown before or after add item, so I included both. Overwriting existing implementation would be bad. Note Jon Skeet comment : "No - if you could use List like ObservableCollection, the latter wouldn't need to exist...". – Margus Jul 31 '14 at 10:28