Home > database >  Why don't we create an Event Handler delegate for binding a handler with an event when programm
Why don't we create an Event Handler delegate for binding a handler with an event when programm

Time:10-30

I am creating a Windows Form application in Visual Studio using C#. I am having trouble understanding the concept of Event Handler Delegates.

If I create an event handler for an event using the Properties window, Visual Studio auto generates this code in the Designer file: this.btnLogin.Click = new System.EventHandler(this.btnLogin_Click); However, if I programmatically create the event handler, I don't have to create an Event Handler delegate. btnLogin.Click = btnLogin_Click; Why is that?

CodePudding user response:

However, if I programmatically create the event handler, I don't have to create an Event Handler delegate.

This is where you're mistaken. You are creating an EventHandler instance, you're just doing it via a method group conversion instead of a delegate creation expression. It's just different syntax for the same thing.

Note that there's nothing special about EventHandler here. Here's an example of the same thing with Action (which is about the simplest delegate there is):

using System;

class Program
{
    static void Main()
    {
        // Delegate creation expression
        Action action1 = new Action(MyMethod);
        // Method group conversion
        Action action2 = MyMethod;
    }

    static void MyMethod() {}
}
  • Related