Introduction: Event in C# is a way for a class to provide notifications to client of that some one interesting thing happens to an object the most use for event in graphical user interface. event provide a generally useful way for objects to single state changes that may be useful to clients of that object. event are an important building block for creating classes that can be reuse in a large number of different programs. Here a simple program show a class ListwithChangedEvent.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyCollections
{
using System.Collections;
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class ListWithChangedEvent : ArrayList
{
public event ChangedEventHandler Changed;
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(EventArgs.Empty);
return i;
}
public override void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}
public override object this[int index]
{
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
}
}
namespace TestEvents
{
using MyCollections;
class EventListener
{
private ListWithChangedEvent List;
public EventListener(ListWithChangedEvent list)
{
List = list;
List.Changed += new ChangedEventHandler(ListChanged);
}
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event Running.");
}
public void Detach()
{
List.Changed -= new ChangedEventHandler(ListChanged);
List = null;
}
}
class Test
{
public static void Main()
{
ListWithChangedEvent list = new ListWithChangedEvent();
EventListener listener = new EventListener(list);
list.Add("item 1");
list.Clear();
listener.Detach();
}
}
}
Ouput of the program:
Thank U. if U have any Suggestions and Comments about my small blog, Plz let me know.