Which is the preferred/recommended way of handling events in .NET:
this.Load += new EventHandler(Form1_Load);
private void Form1_Load(object sender, EventArgs e)
{ }
or
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
What would the pros/cons of each method be? I've used both methods over the years, and have usually leaned more towards the first method simply because that is what Visual Studio creates automatically for handling events. Are there any benefits to the second method that I am missing though?
The first way is what Microsoft suggests. The pattern is:
If you perform the second model, you risk forgetting the base.OnXxx call and breaking everything. Nice part of option 2 is that you get to decide if you are called before or after all of the other event handlers. If you put your code before the base.OnXxx, you get executed before the event does. Of course the first model can be used always, the second only if you are subclassing the class raising the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With