Events in CSharp : Basics
Events in CSharp
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.
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.
Note: Events have no return type.
/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : msdotnetheaven */
// 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();
}
}
}
Difference between Delegates and Events :
There are following two differences:
- Events use delegates.
- Delegates are function pointers they can move across any client.
Popularity: 2%
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.










Leave your response!
You must be logged in to post a comment.