Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the impact of not using MyBase.OnInit(e) when overriding it in a derived class?

Tags:

I'm inheriting from TextBox and overriding OnInit.

Protected Overrides Sub OnInit(e As EventArgs)

MyBase.OnInit(e) 

' I'm adding a dynamic control to go along with my textbox here...
Controls.Add(Something)

End Sub

I have MyBase.OnInit(e) in the example above, but I've been using my control for a while without it, as I forgot to put it in there. This is something I usually do out of habit, so I never gave its purpose much thought:

When overriding OnInit in a derived class, be sure to call the base class’s OnInit method so that registered delegates receive the event.

Slightly embarrassing that this isn't clear to me, but my control works fine, so I was just hoping someone could give an example of what could create an issue.

like image 231
user1447679 Avatar asked Apr 18 '16 00:04

user1447679


1 Answers

Looking at the reference source code for TextBox, if you follow the inheritance up to Control, you see this is the base code for OnInit:

protected internal virtual void OnInit(EventArgs e) {
    if(HasEvents()) {
        EventHandler handler = _events[EventInit] as EventHandler;
        if(handler != null) {
            handler(this, e);
        }
    }
}

So if you don't call base.OnInit, this is what will be missed.

like image 59
DavidG Avatar answered Sep 28 '22 04:09

DavidG