C# > Advanced C# > Delegates and Events > Lambda Expressions

Lambda Expression with Event Handling

This snippet demonstrates how to use a lambda expression to handle an event. It simplifies the event handling process by providing a concise way to define the event handler inline.

Code Example

This code defines a `Button` class with a `Clicked` event. The `EventExample` class then creates an instance of the `Button` class and attaches a lambda expression to the `Clicked` event. The lambda expression `(sender, e) => { Console.WriteLine("Button was clicked!"); }` is executed when the `Clicked` event is raised. The `SimulateClick` method raises the event, triggering the lambda expression.

using System;

public class Button
{
    public event EventHandler Clicked;

    public void SimulateClick()
    {
        Clicked?.Invoke(this, EventArgs.Empty);
    }
}

public class EventExample
{
    public static void Main(string[] args)
    {
        Button myButton = new Button();

        // Use a lambda expression to handle the Clicked event
        myButton.Clicked += (sender, e) =>
        {
            Console.WriteLine("Button was clicked!");
        };

        // Simulate a button click
        myButton.SimulateClick(); // Output: Button was clicked!
    }
}

Concepts Behind the Snippet

Events are a mechanism for a class or object to notify other classes or objects when something of interest happens. Event handlers are methods that are executed when an event is raised. Lambda expressions provide a concise way to define event handlers inline, making the code more readable.

Real-Life Use Case

Event handling with lambda expressions is commonly used in GUI applications (like WPF or WinForms) to handle user interactions such as button clicks, mouse movements, and key presses. It simplifies the process of attaching event handlers to UI elements.

Best Practices

When using lambda expressions for event handling, ensure that the lambda expression is short and focused on the specific event. For more complex logic, consider using a named method as the event handler.

When to use them

Use lambda expressions for event handling when you need a simple, inline event handler. If the event handler requires more complex logic or needs to be reused, consider using a named method instead.

Interview Tip

Understand how events and delegates work together. Events are based on delegates and provide a way to encapsulate the invocation list of a delegate, preventing external classes from arbitrarily raising or clearing the event. Lambda expressions make event handling more concise.

Pros

Conciseness: Lambda expressions provide a more compact syntax for defining event handlers compared to traditional methods.
Readability: Inline event handlers can improve code readability, especially for simple event handling logic.
Reduced Boilerplate: They eliminate the need to define separate named methods for simple event handling tasks.

Cons

Complexity: For complex event handling logic, lambda expressions can become difficult to read and maintain.
Debugging: Debugging lambda expressions can be more challenging compared to debugging named methods.
Reusability: Lambda expressions are not easily reusable across multiple events or classes.

FAQ

  • What is an event?

    An event is a mechanism that allows a class or object to notify other classes or objects when something of interest happens.
  • How do I unsubscribe from an event?

    Use the `-=` operator to unsubscribe from an event. For example: `myButton.Clicked -= (sender, e) => { ... };`