hokapoka
hokapoka

Reputation: 479

C# OnAdd / OnRemove / OnModified event for List<T>.<some action>(objT)

I have a property, say MyList, that's of Type List<int>.

In the set clause of the property some other logic is executed.

I'd like to execute the same logic when the List is modified.

public class MyType
{
    public List<int> MyList
    {
        get { return _MyList; }
        set
        {
            listUpdate(); 
            _MyList = value; 
        }
    }
    private List<int> _MyList

    private void listUpdate()
    {
        // Do something... 
    }
}

I know I could create my own class that inherited from List<T> and override all of the methods that modify the List but wondered if anyone had a better idea?

Upvotes: 2

Views: 1123

Answers (3)

Kasyx
Kasyx

Reputation: 3200

You can do it easly with ObservableCollection. It has also special constructor for List:

public ObservableCollection(
      List<T> collection
)

You can read about it there: http://msdn.microsoft.com/en-us/library/ms653202.aspx

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45048

You could consider using an ObservableCollection which gives notification of modifications:

Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174349

Yeah, I have a better idea. Use ObservableCollection<T>.
It has been created exactly for your purpose. The event you want to subscribe to is CollectionChanged. It is called for all changes.

Upvotes: 8

Related Questions