Introduction
List<T>
provides no events when the count of the list-items is changed. This article provides a class that notifies with a event when the number of the elements is changed.
The class provides a basic approach to this. Further members can be added if needed.
Using the Code
An example will show the usage of this class:
using System;
using gfoidl.Tools;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
gfList<int> list = new gfList<int>();
list.CountChanged +=
new EventHandler<gfList<int>.ListEventArgs>
(list_CountChanged);
list.Add(1);
list.AddRange(new int[] { 2, 3, 4, 5 });
list.Remove(3);
list.Clear();
Console.ReadKey();
}
private static void list_CountChanged(
object sender,
gfList<int>.ListEventArgs e)
{
Console.WriteLine(e.Count);
}
}
}
Implementation
using System;
using System.Collections.Generic;
namespace gfoidl.Tools
{
public class gfList<T> : List<T>
{
#region Event(s)
public event EventHandler<ListEventArgs> CountChanged;
#endregion
#region Methods
public new void Add(T item)
{
base.Add(item);
EventHandler<ListEventArgs> tmp = CountChanged;
if (tmp != null)
tmp(this, new gfList<T>.ListEventArgs(this.Count));
}
public new void AddRange(IEnumerable<T> collection)
{
base.AddRange(collection);
EventHandler<ListEventArgs> tmp = CountChanged;
if (tmp != null)
tmp(this, new gfList<T>.ListEventArgs(this.Count));
}
public new void Clear()
{
base.Clear();
EventHandler<ListEventArgs> tmp = CountChanged;
if (tmp != null)
tmp(this, new gfList<T>.ListEventArgs(this.Count));
}
public new void Remove(T item)
{
base.Remove(item);
EventHandler<ListEventArgs> tmp = CountChanged;
if (tmp != null)
tmp(this, new gfList<T>.ListEventArgs(this.Count));
}
#endregion
#region Subclasses
public class ListEventArgs : EventArgs
{
public int Count { get; set; }
public ListEventArgs(int anzahl)
{
this.Count = anzahl;
}
}
#endregion
}
}
History
- 6th December, 2008: Initial release