Francois Beaussier & Aymeric Gaurat Apelli

Wednesday

Should I use Page_Init or OnInit ?

I came across an interesting issue last friday.

There was an empty Page_Init method in some web control. I removed it, thinking that it would not do any harm.

Well, in fact, it was actually hidding the base class Page_Init method which used not to be executed. Of course, after my change, the base method was called and that caused a crash in the application :)

What I have learned from that:

When creating a base class that requires initialization, it's better to use the OnInit method, rather that the Page_Init.

When using OnInit, the derived class will have to explicitly use the override keyword, which may help other developers avoiding this kind of issues.

2 Comments:

  • This advice seems backwards to me. Page_Init is an event handler, so there is no way it would be overriding something in a base class (you can have many event handlers registered to a single event). By contrast, OnInit is overriding a method on the Control class, which will keep the base method from executing unless you call base.OnInit();

    So, the correct answer is actually, use events, they are less likely to cause strange behavior.

    By Blogger Robin Clowers, at 4:15 am  

  • yes but the Init event is fired from the base class, i.e. the Page, therefore if you override the OnInit method you can add your custom code before explicitly invoking the base.OnInit() method.

    I'd have to side with Francoise on this one, but good discussion.

    By Anonymous Mike, at 10:43 pm  

Post a Comment

<< Home