2

i have following class:

public class FirstClass 
{
   public FirstClass()
   {
       list = new List<SomeType>();
   }

   public List<SomeType> list;
}

Is this possible to do some actions like fire different method after someone will put element into that list?

kosnkov
  • 5,609
  • 13
  • 66
  • 107
  • You deleted your question about creating a variable in C#. But just FYI, I asked a similar question before for curiosity: http://stackoverflow.com/questions/7478833/is-it-possible-to-create-variables-at-runtime-in-java It's in Java but most of the answers apply to C# as well. – NullUserException Apr 11 '12 at 19:39

5 Answers5

5

You should use a ObservableCollection<SomeType> for this instead.

ObservableCollection<T> provides the CollectionChanged event which you can subscribe to - the CollectionChanged event fires when an item is added, removed, changed, moved, or the entire list is refreshed.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
4

Maybe you should be using ObservableCollection<T>. It fires events when items are added or removed, or several other events.

Here is the doc: http://msdn.microsoft.com/en-us/library/ms668604.aspx

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
2

List does not expose any events for that. You should consider using ObservableCollection instead. It has CollectionChanged event which occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

you can do something like

        private List<SomeType> _list;

        public void AddToList(SomeType item)
    {
        _list.Add(item);
        SomeOtherMethod();
    }

      public ReadOnlyCollection<SomeType> MyList
    {
       get { return _list.AsReadOnly(); }
}

but ObservableCollection would be best.

Stephen Gilboy
  • 5,572
  • 2
  • 30
  • 36
0

If you create your own implementation of IList you can call methods when an item is added to the list (or do anything else you want). Create a class that inherits from IList and have as a private member a list of type T. Implement each of the Interface methods using your private member and modify the Add(T item) call to whatever you need it to do

Code:

public class MyList<T> : IList<T>
{
    private List<T> _myList = new List<T>();

        public IEnumerator<T> GetEnumerator() { return _myList.GetEnumerator(); }
        public void Clear() { _myList.Clear(); }
        public bool Contains(T item) { return _myList.Contains(item); }

        public void Add(T item) 
        { 
            _myList.Add(item);
            // Call your methods here
        }

         // ...implement the rest of the IList<T> interface using _myList
   }
Dan Busha
  • 3,723
  • 28
  • 36