I had an interview a week ago and one of the questions was what the difference between OnInit, Page_Init and PreRender. which one is preferable?
1 Answer
Page_Init is an event handler for the Page.Init event, you typically see it if you add a handler within the class itself.
OnInit is a method that raises the Init event.
The two can be seen as being equivalent if used within a subclass, but there is a difference: only Init is exposed to other types, the OnInit method is protected and is responsible for raising the event, so if you override OnInit and fail to call base.OnInit then the Init event won't be fired. Here's how it looks like:
public class Page {
public event EventHandler Init;
public event EventHandler Load;
protected virtual void OnInit(Object sender, EventArgs e) {
if( this.Init != null ) this.Init(sender, e);
}
protected virtual void OnLoad(Object sender, EventArgs e) {
if( this.Load != null ) this.Load(sender, e);
}
public void ExecutePageLifecylce() {
this.OnInit();
// do some houskeeping here
this.OnLoad();
// further housekeeping
this.Dispose();
}
}
public class MyPage : Page {
public MyPage() {
this.Init += new EventHandler( MyPage_Init );
}
private void MyPage_Init(Object sender, EventArgs e) {
// No additional calls are necessary here
}
protected override void OnLoad(Object sender, EventArgs e) {
// you must make this following call for any .Load event handlers to be called
base.OnLoad(sender, e);
}
}
Generally overriding the OnLoad / OnInit methods is faster (but this is a microptimisation, you're only saving a couple of extra instructions for delegate dispatch) and many "purists" will argue using events unnecessarily is just ugly :)
Another advantage of not using events is avoiding bugs caused by AutoEventWireUp which can cause events to be called twice for each page load, which obviously is not desirable if your event-handlers are not idempotent.
OnInit()will fire even if you turn off auto event wire up. That said,OnXxx()methods should arguably be used to change the logic for whether / how to raise an event, not to handle it. (Although it's mostly a wash.) It also lets you do something before the regularOnInit()logic, but then again your code's correct behaviour shouldn't depend on those timing details, seems very fragile to me. I've no idea whyPreRenderwould be mentioned, it's on the opposite side of the page rendering lifecycle and should be used for vastly different purposes.Page_Init,Page_LoadandPage_PreRender?