Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I have a have a void inside an event handler declaration?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading