What is the difference between Events with Delegate Handlers and those without?

StackOverflow https://stackoverflow.com/questions/119160

  •  02-07-2019
  •  | 
  •  

Question

What is the difference between this:

this.btnOk.Click += new System.EventHandler(this.btnOK_Click);

and this?

this.btnOk.Click += this.btnOK_Click;

They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing something?

Was it helpful?

Solution

No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood.

OTHER TIPS

In C# 3.0 and later this is no difference. Before C# 3.0 EventHandlers were required due to compiler limitations, but with the advent of C# 3.0, the second form is preferred unless you want to be very explicit.

I believe that C# since 3.0 has implicitly added the delegate handler. However, it can help to be more explicit, especially when there are multiple possible delegate types.

"+= Delegate_Name" is a syntax sugar. Compiler will create new wrapper for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top