Home > Enterprise >  Can I have a have a void inside an event handler declaration?
Can I have a have a void inside an event handler declaration?

Time:12-03

I have a button on my C# Winform, and the following code:

button1.Click  = button1_Click;

and also:

private static void button1_Click(object sender, EventArgs e)
{
    // do something
}

I am trying to simplify and reduce the amount of code in my application. Is there any way to do this? Here's what I am trying to achieve:

button1.Click  =  void button1_Click(object sender, EventArgs e)
{
    // do something
};

This does not work. Is there any other way to achieve this?

CodePudding user response:

You can do this with an anonymous method:

button1.Click  = (sender, e) =>
{
   // do something
};

But note that you will never be able to unregister this event handler as it is an anonymous method.

  • Related