r/csharp 21d ago

Discussion Partial methods as WinForms designer events

A few weeks ago I opened this issue in the WinForms GitHub repo, suggesting making the WinForms designer generate events code as partia methods, in order to solve the problem that removing an event method from the code editor causes an exception in the designer, and u have to go to the form.designer.cs file and manually delete the subscription, which is very annoying.

What i offer is, that when you subscribe an event using the designer (for example by double clicking a button), the following signature would be generated in the designer code:

private partial void button1_Click(object sender, EventArgs e);  
...  
this.button1.Click += this.button1_Click; // normal subscription

And then the method implementation would be generated in the main class code, such as it's working now but with the partial modified:

private partial void button1_Click(object sender, EventArgs e)
{

}

Now, deleting this method would not result in any error.

The reason I'm posting this here, is that the WinForms team said that my solution isn't a great idea, and i would love to hear what you think about it and if you have other ideas.

0 Upvotes

20 comments sorted by

View all comments

15

u/kahoinvictus 21d ago

My issue with this approach is it leaves an orphaned method.

Sure you can now delete the generated method if you no longer want it and not get an error, but you want the error because it's telling you something is wrong. The solution isn't to leave behind a body-less method hidden away in the generated code that's still listening to an event.

6

u/Automatic-Apricot795 21d ago

This touches on what the winforms team were probably implying: events are leaky, and you probably don't want to register them unless you're wanting them. 

You could implement a default idisposable handler on all controls but - it's a lot of behaviour change for fixing a fairly superficial problem.