By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,587 Members | 1,071 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,587 IT Pros & Developers. It's quick & easy.

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

codegecko
Expert 100+
P: 533
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
Feb 4 '09 #1
Share this Question
Share on Google+
3 Replies


100+
P: 179
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.

Expand|Select|Wrap|Line Numbers
  1. public class ListCountChang<T> : List<T>
  2. {
  3.     public event EventHandler CountChangeEvent;
  4.  
  5.     public void Add(T item)
  6.     {
  7.         base.Add(item);
  8.         CountChange();
  9.     }
  10.  
  11.    public void AddRange(IEnumerable<T> items)
  12.    {
  13.         base.AddRange(items);
  14.         CountChange();
  15.    }
  16.  
  17.     private void CountChange()
  18.     {
  19.          if(CountChangeEvent != null)
  20.          {
  21.              CountChangeEvent(this, EventArgs.Empty);
  22.          }
  23.     }
  24. }
  25.  
  26.  
Feb 4 '09 #2

vekipeki
Expert 100+
P: 229
You will probably have to override System.Collections.ObjectModel.Collection<T>, since I think List<T> methods are not virtual.
Feb 5 '09 #3

100+
P: 179
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 :)
Feb 5 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.