Is delegate necessary?

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

Hi,

A typical way of using delegates, for example, is:

class MyForm
{

void Button1.Click += new EventHandler (Action1);
void Button1.Click += new EventHandler (Action2);
void Button1.Click += new EventHandler (Action3);
}

This is equivalent to the following:

class MyForm
{

void Button1.Click()
{
Action1;
Action2;
Action3;
}
}

Therefore, delegates can be replaced by regular method calls. I don't
see the need to use delegates. Anyone could explain why use them?
 
If you take someone else's class and want *your* methods to file when
*their* process milestones or events (i.e. click) occur, what are you going
to do to get them to wire up your methods to their class, i.e. put your
Action1 into their Click()? .. Call them up on the phone? "Yes, hi, sorry
for bothering you, can you please fire my custom Click() event?"

Event binding via delegates allows whoever's raising the event to trigger
the methods without necessarily knowing what they are. It's actually very
powerful--think passing a reference to your method as though it were a
string or some other variable, and let these other objects fire off your
code at the right times without you having to call your method yourself.

Incidentally, this is impossible:

class MyForm
{

void Button1.Click()
{
...
}
}

You're inferring that your MyForm class will handle the Click() event on
Button1. It won't. The dot also makes for bad syntax.

But you can declare a "void Click()" method and reference that in a delegate
so that Button1 calls your Click() method.

class MyForm
{
void Form_Load(object sender, EventArgs e)
{
Button1.Click += new EventHandler(Button1_Click);
}

void Button1_Click(object sender, EventArgs e)
{
Action1();
Action2();
Action3();
}
}
 
Back
Top