Question

At work, my old boss would insist we programmatically assign and remove event handlers from our controls in the code behind, rather than simply double clicking a button (for example).

We'd have an AttachEvents() and DetachEvents() method on every single form. I don't remember his explanation as to why this is allegedly better than assigning it from the Design View, and he's since been transferred to a different project. My new manager doesn't know.

I thought he said it had something to do with events not properly being removed from memory, but I really don't know.

So: What is the benefit of doing it this way?

No correct solution

OTHER TIPS

Performance-wise they are the same. But doing it in the code behind is a much neater way since you control when to AttachEvents() or DetachEvents()

But you have to be careful in terms of avoiding any duplicate event wire ups. These in turn might lead up eating memory, but prominently they would cause performance issues since the event handler would be called as many times as it was wired up.

Some event handlers such as timers need to be removed before leaving a form otherwise they would still fire, for example timer.Elapsed += ... and timer.Elapse -= ... Probably a good and clear way to remember to do it in this way.

Other than the implications of your own architecture, there's no difference whatsoever.

The designer will place the event subscriptions on the InitializeComponent method and you should not do any changes to that method because the designer might override them or crash if it's something it can't handle.

Usually, the event subscriptions are events the form subscribes from its children. When the from is closed/disposed, all the children are disposed and each child will dispose event subscriptions.

Problems arise when the form subscribes to outside components. Then the form becomes "attached" to those components and, if not unsubscribed, becomes a resource leak.

There's also the possibility of events being fired when the form is not ready to handle them.

I've used a mixed approach where events from child controls were subscribed in the designer (or carefully manually coded in the InitializeComponent method) and used the AttachEvents/DetachEvents approach for components outside the UI (or the scope of the form/control).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top