8

Someone mentioned to me that c# supports to use lambda expression as event handler, can anyone share with me some reference on this?

A code snippet is preferred.

0

2 Answers 2

13

You can use a lambda expression to build an anonymous method, which can be attached to an event.

For example, if you make a Windows Form with a Button and a Label, you could add, in the constructor (after InitializeComponent()):

 this.button1.Click += (o,e) =>
     {
        this.label1.Text = "You clicked the button!";
     };

This will cause the label to change as the button is clicked.

Sign up to request clarification or add additional context in comments.

4 Comments

Yup. I also wanted to point this out regarding adding and removing anonymous event handlers: stackoverflow.com/questions/2051357/…
@devshorts Yes. It's not necessarily great if you need to unsubscribe as well.
Aren't the braces redundant for single-statement method bodies?
@Superbest They're not necessary for single statement bodies - they don't hurt anything, though, and it makes it a bit more clear when reading in a post like this, which is why I wrote it that way.
0

try this example

public Form1()
{
    InitializeComponent();
    this.button1.Click += new EventHandler(button1_Click);
}

void button1_Click(object sender, EventArgs e)
{
}

The above event handler can be rewritten using this lambda expression

public Form1()
{
    InitializeComponent();
    this.button1.Click += (object sender, EventArgs e) = >
    {
        MessageBox.Show(“Button clicked!”);
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.