0

Possible Duplicate:
C#: Difference between ‘ += anEvent’ and ‘ += new EventHandler(anEvent)’

Hi all,

I have two eventhandlers.

In my constructor I attach a function to the eventhandler but do it in different ways for the two eventhandlers. One with new Eventhandler, the other by just pointing to the function. They seem to do the same?

What is the prefered way and why?

UPDATE: already answered here

public partial class MyForm : Form
{
    public event EventHandler Button1Clicked;
    public event EventHandler Button2Clicked;

    public MyForm()
    {
        InitializeComponent();

        simpleButton1.Click += new EventHandler(simpleButton1_Click);
        simpleButton2.Click += Button2Click;
    }

    void simpleButton1_Click(object sender, EventArgs e)
    {
        if (Button1Clicked != null)
        {
            Button1Clicked.Invoke(sender, e);
        }
    }

    void Button2Click(object sender, EventArgs e)
    {
        if (Button2Clicked != null)
        {
            Button2Clicked.Invoke(sender, e);
        }
    }
}
Community
  • 1
  • 1
Tarscher
  • 1,923
  • 1
  • 22
  • 45
  • 2
    The are the same. The `new EventHandler` code is now syntactic sugar and not necessary any more. – ChrisF Jul 02 '10 at 09:28

3 Answers3

3

C# 2 introduced method group conversions which is what your second form is using. It does exactly the same thing internally - in both cases, it produces a new instance of EventHandler.

Personally I prefer the second form: it doesn't have as much cruft. It just says what you're interested in.

(I hadn't spotted the exact duplicate. Leaving this answer here despite closing the question, as it's doing no harm.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

yes they do the same. Resharper recomemnds latter.

Arseny
  • 7,251
  • 4
  • 37
  • 52
1

Both of the way of attaching event handler are same. In the last case framework (fro 2.0 onward) is able to infer type itself.

crypted
  • 10,118
  • 3
  • 39
  • 52