The difference between = anEvent
and = new EventHandler(anEvent)
in C#
Lambda expressions in C# simplify the syntax for adding event handlers, leading to two common practices:
1. = anEvent
button1.Click = anEvent;
anEvent
is a delegate that refers to the method to be executed when the event occurs. The compiler automatically infers the correct delegate type based on the method signature. 2. = new EventHandler(anEvent)
button1.Click = new EventHandler(anEvent);
EventHandler
) before assigning the event handler. The difference between the two methods
The fundamental difference lies in the delegated inference mechanism:
Summary: They are equivalent
Both methods can achieve the same functionality. Which method you choose comes down to personal preference. For C# 2.0 and higher projects, use = anEvent
to make your code cleaner, and = new EventHandler(anEvent)
to explicitly define delegate types.
The above is the detailed content of C# Event Handling: What's the Difference Between ` = anEvent` and ` = new EventHandler(anEvent)`?. For more information, please follow other related articles on the PHP Chinese website!