C# - list.Count property - how to catch?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JamieHowarth0
    Recognized Expert Contributor
    • May 2007
    • 537

    C# - list.Count property - how to catch?

    Hi guys,

    Is there a way of either altering a list class, or creating some kind of listener, that throws an event when the Count property of a list changes?

    Cheers,

    codegecko
  • IanWright
    New Member
    • Jan 2008
    • 179

    #2
    How about something like this? Obviously you'll need to cover all the changes that can adjust the number of items contained within the list.

    Code:
    public class ListCountChang<T> : List<T>
    {
        public event EventHandler CountChangeEvent;
    
        public void Add(T item)
        {
            base.Add(item);
            CountChange();
        }
    
       public void AddRange(IEnumerable<T> items)
       {
            base.AddRange(items);
            CountChange();
       }
    
        private void CountChange()
        {
             if(CountChangeEvent != null)
             {
                 CountChangeEvent(this, EventArgs.Empty);
             }
        }
    }

    Comment

    • vekipeki
      Recognized Expert New Member
      • Nov 2007
      • 229

      #3
      You will probably have to override System.Collecti ons.ObjectModel .Collection<T>, since I think List<T> methods are not virtual.

      Comment

      • IanWright
        New Member
        • Jan 2008
        • 179

        #4
        vekipeki,

        That sounds like a better idea. I tried something slightly different using the List.Count property as I originally misread the post, and although the methods were not virtual on the List it did work.

        The new operator may work for hiding, but then I'm not sure if you can still call the base if you do that....

        I think Collection<T> is probably the way to go too :)

        Comment

        Working...