I'm a newbie in events. This example shows that an event is invoked every time the ArrayList is changed. I would like to know how to do it using generics. To you implement IList or extend List? I tried to code it but I'm stuck.
using System;
using System.Collections.Generic;
namespace Events
{
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class ListWithChangedEvent<T> : IList<T>
{
public event ChangedEventHandler Changed;
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
public void Add(T value)
{
base.Add(value);
OnChanged(EventArgs.Empty);
}
public void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}
public T this[int index]
{
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
}
class EventListener
{
private ListWithChangedEvent<string> List;
public EventListener(ListWithChangedEvent<string> list)
{
List = list;
List.Changed += new ChangedEventHandler(ListChanged);
}
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
public void Detach()
{
List.Changed -= new ChangedEventHandler(ListChanged);
List = null;
}
}
class Program
{
public static void Main(string[] args)
{
ListWithChangedEvent<string> list = new ListWithChangedEvent<string>();
EventListener listener = new EventListener(list);
list.Add("item 1");
list.Clear();
listener.Detach();
}
}
}