1

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?

Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • Does this answer your question? [C# delegate: literal constructor](https://stackoverflow.com/questions/30831469/c-sharp-delegate-literal-constructor) – Charlieface Oct 30 '22 at 13:01
  • 1
    @Charlieface you literally linked a question that is duplicate of duplicate of duplicate. – grandsirr Oct 30 '22 at 20:08
  • @GrandSirr If I was gold badge I would have linked all of them. This way a gold-badger can link them all. – Charlieface Oct 30 '22 at 20:12
  • A delegate is a reference type. In terms of data structure, a delegate is a user-defined type just like a class. When the delegate is called, all methods contained in the delegate will be executed. – sssr Nov 01 '22 at 06:57

1 Answers1

3

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() {}
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194