Search This Blog

2009-12-01

Tutorial 13:Events

An event is a member that enables an object or class to provide notifications.
As compared to delegates events works with source and listener methodology. So listeners who are interested in receiving some events they subscribe to the source. Once this subscription is done the source raises events to its entire listener when needed. One source can have multiple listeners.
In C# events are based on delegates, with the originator defining one or more call back functions. A call back function is a function in which one piece of code defines another implements, in other words, one piece of code says, “If you implement a function which looks like this, I can call it”. A class that wants to sue events defines callback functions or delegates, and the listening object then implements them.
Events have no return type.
There are following two differences:
1. Events use delegates.
2. Delegates are function pointers they can move across any client.

// File name : events.cs
using System;
namespace CSharp.AStepAhead.events
{
class Button
{
public event EventHandler Click;
public void Reset()
{
Click = null;
}
}
public class impButton
{
Button Button1 = new Button();
public impButton()
{
Button1.Click += new EventHandler(Button1_Click);
}
public void Connect()
{
Console.WriteLine("Attaching the event handler");
Button1.Click += new EventHandler(Button1_Click);
}
void Button1_Click(object s, EventArgs e)
{
Console.WriteLine("Button1 clicked!");
}
public void Disconnect()
{
Console.WriteLine("Removng the event handler");
Button1.Click -= new EventHandler(Button1_Click);
}
static void Main()
{
impButton objButton = new impButton();
objButton.Connect();
Console.ReadLine();
objButton.Disconnect();
Console.ReadLine();
}
}
}

No comments: