views:

857

answers:

2

Using VS2008, C#. When AutoEventWireup is set to true and in a webform I call base.OnLoad(e) like

protected void Page_Load(object sender, EventArgs e) { base.OnLoad(e); }

The base.OnLoad(e) ends up calling Page_Load (calls itself). This ends up with a stack overflow error. I've been able to solve it by setting AutoEventWireup to false and overriding OnLoad:

protected override void OnLoad(EventArgs e) { base.OnLoad(e); }

This works as I expected (no stack overflows). But can anyone explain why in the first example base.OnLoad(e) calls the same load event (calls itself) rather than calling the OnLoad event in the base class (System.Web.UI.Page)?

+3  A: 

OnLoad doesn't call itself, it calls the Load event. The Page.OnLoad method merely wraps the call to the attached events. You should not call base.OnLoad from a Load event handler or it will result in an infinite loop.

BC
But why is base.OnLoad(e) not calling the Load event of the base class?
Ben Amada
It does. That is why handling the Load event and calling base.OnLoad causes an infinite loop.
BC
But in the 2nd example I have where I override the OnLoad event (and AutoEventWireup is false), base.OnLoad(e) is being called there too without any infinite loops. Isn't my OnLoad handler in the 2nd example also handling the load event ... why no infinite loop in that case?
Ben Amada
That's because you're not handling the Load event using Page_Load. You're confusing OnLoad and Page_Load -- one is a virtual method and one is an event handler.When you override OnLoad, and call base.OnLoad, base.OnLoad then calls the Load event, which doesn't exist! No loop!
BC
Makes a lot of sense now. You're right, I was incorrectly thinking of the OnLoad override as being an event handler, which it isn't. Thanks for your patience :)
Ben Amada
+2  A: 

Page.OnLoad has the following pseudo-code inside it

protected virtual void OnLoad() {
    // some stuff

    if (Load != null)
        Load(this, new EventArgs());
}

if you override the OnLoad function, what happens is: Your OnLoad happens, then it calls base.OnLoad(), and that calls the (empty) Load event.

If you implement the Load event and call base.OnLoad(), this is what happens: base.OnLoad() calls the Load event. The Load event then calls base.OnLoad(). Then, base.OnLoad() calls the Load event. And the rest is, as they say, to understand recursion you must first understand recursion.

Hope I made myself clear.

configurator
Between your answer, BC's answer and testing your answers in Visual Studio, I've _finally_ caught on. Thank you.
Ben Amada
Also, sorry I have no reputation to up-vote you :(
Ben Amada