delegate or event handler?

  • Thread starter Thread starter ALI-R
  • Start date Start date
A

ALI-R

What is the difference between implementing an Event using a Deligate or an
Event Handler?,look at below

1)this.button1.Click += new System.EventHandler(this.button1_Click);
...............
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("You have clicked btn1);
}



2) public delegate void ClickEvent (object sender, System.EventArgs e);
public event ClickEvent OnClickbtn1;
..............
OnClickbtn1 +=new ClickEvent (button1_Click)
..............
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("You have clicked btn1);
}
 
They are equivalent. System.EventHandler is a delegate.

From the online help:
"[Serializable]
public delegate void EventHandler(object sender, EventArgs e);"

ShaneB
 
ALI-R,

1) Assuming you have a button on the form named button1
what is happening is that when you click the button, Click event is
triggered, and using new System.EventHandler(this.button1_Click);
tells the program that when this event happen please call this (these)
function(s).

2) Same thing but in this case when button is clicked nothing will happen
until you call OnClickbtn1 from some place. OnClickbtn1 is your event and it
will not react to the events happening inside button1. So, in other words
you can call button1_Click(object sender, System.EventArgs e) from your own
functions or events.

Thanks,
Ashish
 
oops... I should have read this line more carefully before I hit Send :)

I thought it read:
ShaneB
 
ALI-R said:
What is the difference between implementing an Event
using a Deligate or an Event Handler?,look at below
1)this.button1.Click += new System.EventHandler(...

Nothing. EventHandler is a delegate.

P.
 
I don't believe there is any different from the *functionality* point of
view, however from the *compiler* perspective the "event" keyword makes all
the difference.



The compiler treats the event as a special delegate. The main reason for
this is to protect the programmer from screwing up when dealing wit
multicast delegates (a delegate referring to more than one function).

Please check out the following link, its very informative:
http://www.sellsbrothers.com/writing/default.aspx?content=delegates.htm


Hope this helps.
 
Back
Top