Donovan Keating Donovan Keating - 1 year ago 112
C# Question

C#: EventHandler delegate

public delegate void EventHandler(object sender, EventArgs e);


In the above code, EventHandler is a delegate which accepts
object sender, EventArgs e
. However, the number of arguments do not match in the below implementation:

this.baptismApplication_add_button.Click += new System.EventHandler(this.baptismApplication_add_button_Click);


I can see that the
sender
is
this.baptismApplication_add_button_Click
, but which part of the method calls has
EventArgs e
? Is it implicit? Or am I going about this all wrong?

Answer Source

delegate are special types. They represent methods. This:

public delegate void EventHandler(object sender, EventArgs e);

does not mean that to create an EventHandler, you need to pass in two arguments sender and e. It simply means

EventHandler represents a method with the signature of (object sender, EventArgs e) returning void.

To create a EventHandler, you need to pass in a method that has the required signature. For example, this method:

private void MyMethod(object sender, EventArgs e) {

}

You can create an EventHandler like this:

new EventHandler(MyMethod);

Note how I did not write () after the method name. Doing so would call the method. We don't want that. Here we just want to refer to it.

Let's look at another example.

public delegate void Action();

To create an Action, you need a method that has no arguments and returns void. Like this:

private void MyMethod2() {}
// ...
new Action(MyMethod2);

Now that you understood how delegates work, we can talk about how to subscribe to the Click event properly.

As I've said, EventHandler's "constructor" takes a method as argument, so you shouldn't pass your button in there. You need a method. Let's write one:

private void ButtonPressed(object sender, EventArgs e) {
    Console.WriteLine("Hello World");
}

Now we can create the delegate with this method:

yourButton.Click += new EventHandler(this.ButtonPressed);

This can actually be shortened to:

yourButton.Click += ButtonPressed;

Now every time you press the button "Hello World" will be printed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download