Anonymous new event handler with lamda
In C#, you can create an anonymous event handler using a lambda expression. Here's an example:
button.Click += (sender, e) => Console.WriteLine("Button clicked!");
In this example, the lambda expression (sender, e) => Console.WriteLine("Button clicked!");
is an anonymous method that will be called when the Click
event is raised on the button
object.
Here's a breakdown of the lambda expression:
(sender, e)
is the input parameter list, which matches the signature of the event handler method. In this case, the method takes two parameters:sender
(the object that raised the event) ande
(the event arguments).=>
is the lambda operator, which separates the input parameters from the method body.Console.WriteLine("Button clicked!");
is the method body, which is the code that will be executed when the event is raised.
By using a lambda expression, you can create a concise and expressive event handler without having to declare a separate method.
Note that you can also use a lambda expression to create an event handler that takes no parameters, like this:
button.Click += () => Console.WriteLine("Button clicked!");
In this case, the lambda expression takes no input parameters, and the method body is simply Console.WriteLine("Button clicked!");
.