hi i have this sample from msdn.
using System;
using System.Collections;
namespace ListChangedEvents
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public delegate void ChangedEventHandler(Object sender, EventArgs e);
public class ListWithChangedEvent : ArrayList
{
public event ChangedEventHandler Changed;
public ListWithChangedEvent()
{
}
protected virtual void OnChanged(EventArgs e)
{
Changed(this,e);
}
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(EventArgs.Empty);
return i;
}
public override void Insert(int index, object value)
{
base.Insert (index, value);
OnChanged(EventArgs.Empty);
}
public override void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}
public override object this[int index]
{
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
}
class EventListener
{
private ListWithChangedEvent List;
public EventListener(ListWithChangedEvent list)
{
List = list;
// Add "ListChanged" to the Changed event on "List".
List.Changed += new ChangedEventHandler(ListChanged);
}
// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
public void Detach()
{
// Detach the event and delete the list
List.Changed -= new ChangedEventHandler(ListChanged);
List = null;
}
}
class Test
{
// Test the ListWithChangedEvent class.
public static void Main()
{
// Create a new list.
ListWithChangedEvent list = new ListWithChangedEvent();
// Create a class that listens to the list's change event.
EventListener listener = new EventListener(list);
// Add and remove items from the list.
list.Add("item 1");
list.Clear();
listener.Detach();
list.Insert(1,"val");
//list.Add("item 2");
}
}
}
I want to do away with the Eventlistener class becos in a real world
application do we need this class. cant i listen to events from the
ListWithChangedEvent class?
does that sound right?
thanx