views:

221

answers:

4

Lets say we have a form consisting of 20+ controls, for example buttons. We want to create handlers for the On-click event for all of them.

The usual way is to go to the designer and double-click each button to have it automatically create the function. Another way is to create them yourself in code, after the InitializeComponent() function.

Is the difference between the two? 1) In performance 2) In speed 3) Garbage collecting

The first way is easy but lately I've been thinking about the second because its easy to see (in one place) what controls have what events handled without going to the designer which is a real pain if you have the controls cluttered...

+4  A: 

Creating them through the designer is exactly the same as defining them in code yourself.

What actually happens is they are placed within the InitializeComponent() method on the form, which is normally in the designer.cs file. So it's there, it's just a little more hidden from the developer.

This means that neither performance/speed nor garbage collection will be affeted in anyway :)

Ian
A: 

There's no difference in performance speed or garbage collection. Whether you write the event hander button.OnClick += MyHandler or you double click in the designer and he generates that for you, it's just the same.

There might be a difference in typing button.OnClick += MyHandler and the Visual Studio generated button.OnClick += new EventHandler(MyHandler). Since there's a constructor involved. But that's just a marginal difference.

BennyM
A: 

Why would there be any difference ? When you doubleclick the button in the designer, to create an eventhandler, VS.NET will generate code to attach the eventhandler to the Click event. Actually, the generated code will be the same as the code that you'll write to attach the eventhandler to the event.

Frederik Gheysels
Will I have to unsubscribe from the events if I do it myself?
ThanosPapathanasiou
When you doubleclick in the designer, no code is generated to unsubscribe from the events either.
Frederik Gheysels
A: 

As the other answers stated, there is little to choose between the tow methods other then coding style.

I have worked on a project where the Buttons themselves were attributed data that allowed a generic event handler to determine the action required. This alows the Event Handler code to be nice and simple e.g.

foreach(Control ctrl in this.Controls)
{
    if(ctrl is Button)
    {
        (ctrl as Button).Click += // generic Event handler
    }
}

The downside of this approach is that it tightly couples the button with the event handler code. But in a limited scope application with a set of buttons that perform the same function, this could be a useful techinque.

TK