Implementing events in List
If you want to subscribe for changes to a List<T>
in C# it is very easy. All you need to do, is subclass List<T>
and implement your own event handler. This could be done as following:
using System;
using System.Collections.Generic;
namespace FEwald
{
public class MyList<T> : List<T>
{
/// <summary>
/// EventHandler which is called when items are added.
/// </summary>
public event EventHandler ItemAdded;
/// <summary>
/// EventHandler which is called when items are deleted.
/// </summary>
public event EventHandler ItemRemoved;
/// <summary>
/// Adds an item to the list.
/// </summary>
/// <param name="item"></param>
public new void Add(T item)
{
if (ItemAdded != null)
{
ItemAdded(item, EventArgs.Empty);
}
base.Add(item);
}
/// <summary>
/// Adds a range of items to the list.
/// </summary>
/// <param name="collection"></param>
public new void AddRange(IEnumerable<T> collection)
{
foreach (var item in collection)
{
Add(item);
}
}
/// <summary>
/// Removes an item from the list.
/// </summary>
/// <param name="item"></param>
public new void Remove(T item)
{
if (ItemRemoved != null)
{
ItemRemoved(item, EventArgs.Empty);
}
base.Remove(item);
}
}
}