C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'

C#DelegatesEvent Handling

C# Problem Overview


Take the below code:

private void anEvent(object sender, EventArgs e) {
    //some code
}

What is the difference between the following ?

[object].[event] += anEvent;
   
//and
  
[object].[event] += new EventHandler(anEvent);

[UPDATE]

Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.

C# Solutions


Solution 1 - C#

There is no difference. In your first example, the compiler will automatically infer the delegate you would like to instantiate. In the second example, you explicitly define the delegate.

Delegate inference was added in C# 2.0. So for C# 1.0 projects, second example was your only option. For 2.0 projects, the first example using inference is what I would prefer to use and see in the codebase - since it is more concise.

Solution 2 - C#

[object].[event] += anEvent;

is just syntactic sugar for -

[object].[event] += new EventHandler(anEvent);

Solution 3 - C#

I don't think there is a difference. The compiler transforms the first into the second.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreas GrechView Question on Stackoverflow
Solution 1 - C#driisView Answer on Stackoverflow
Solution 2 - C#Martin JonášView Answer on Stackoverflow
Solution 3 - C#MegacanView Answer on Stackoverflow