Friday, 29 July 2011

Declaring and using delegates in csharp

The following is the simple way to declare and using delegates
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void Startdelegate(); //we can pass any type of parameter ex StartDelegate(string x);

class Eventdemo : Form
{
// custom event
public event Startdelegate StartEvent;

public Eventdemo()
{
Button clickMe = new Button();

clickMe.Parent = this;
clickMe.Text = "Click Me";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) /2,
(ClientSize.Height - clickMe.Height)/2);

// an EventHandler delegate is assigned
// to the button's Click event
clickMe.Click += new EventHandler(OnClickedMe);
// our custom "Startdelegate" delegate is assigned
// to our custom "StartEvent" event.
StartEvent += new Startdelegate(OnStartEvent);

// fire our custom event
StartEvent(); // if pass the parameters while declaring then call like StartEvent("hello")
}

// this method is called when the "StartEvent" Event is fired
public void OnStartEvent()
{
MessageBox.Show("I Just Started!");
}
//this method is called when button is clicked
public void OnClickedMe(object delSender, EventArgs delE)     
    { 
       MessageBox.Show("You Clicked My Button!");  
     };

 static void Main(string[] args)
{
Application.Run(new Eventdemo());
}
}

Note: EventHandler is a builtin type delegate. We can write our own delegates to handle events.

No comments:

Post a Comment