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.

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
Adam Lee
  • 24,710
  • 51
  • 156
  • 236

2 Answers2

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Yup. I also wanted to point this out regarding adding and removing anonymous event handlers: http://stackoverflow.com/questions/2051357/c-sharp-adding-and-removing-anonymous-event-handler – devshorts Oct 09 '12 at 00:11
  • @devshorts Yes. It's not necessarily great if you need to unsubscribe as well. – Reed Copsey Oct 09 '12 at 00:13
  • Aren't the braces redundant for single-statement method bodies? – Superbest Oct 09 '12 at 00:52
  • @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. – Reed Copsey Oct 09 '12 at 01:20
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!”);
    };
}
Johnny
  • 8,939
  • 2
  • 28
  • 33
Nudier Mena
  • 3,254
  • 2
  • 22
  • 22