.netlistc#-4.0fody-propertychanged

What is the best way to check if System.Collections.Generic.List<T> is updated (C# 4.0)?


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.


Solution

  • 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;
            }
        }
    }