asp.net - difference between Page_Init vs OnInit -
i had interview week ago , 1 of questions difference between oninit, page_init , prerender. 1 preferable?
page_init
event handler page.init
event, typically see if add handler within class itself.
oninit
method raises init
event.
the 2 can seen being equivalent if used within subclass, there difference: init
exposed other types, oninit
method protected , responsible raising event, if override oninit
, fail call base.oninit
init
event won't fired. here's how 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(); // 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 necessary here } protected override void onload(object sender, eventargs e) { // must make following call .load event handlers called base.onload(sender, e); } }
generally overriding onload
/ oninit
methods faster (but microptimisation, you're saving couple of instructions delegate dispatch) , many "purists" argue using events unnecessarily ugly :)
another advantage of not using events avoiding bugs caused autoeventwireup
can cause events called twice each page load, not desirable if event-handlers not idempotent.
Comments
Post a Comment