Overriding vs. Event Handling

rbulph

Junior Contributor
Joined
Feb 17, 2003
Messages
397
Is there any practical difference between the two procedures in the following class?

Code:
Public Class Class1
    Inherits PictureBox

    Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Forms.MouseEventArgs)
        If TypeOf Me.Parent Is Form Then Me.Parent.Text = e.X
        MyBase.OnMouseMove(e)
    End Sub

    Protected Sub Class1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
        If TypeOf Me.Parent Is Form Then Me.Parent.Text = e.X
    End Sub

End Class

I suppose the second sub could be Private or Public as well so, in the latter case, it could be called from outside. But is there anything more?
 
Last edited:
Thats an interesting question. To the best of my knowledge when working within a class you should use the override method instead of using an attached event. I couldn't tell you with any accuracy why this is the case though. As an event allows an array of delegates I'm guessing if you attach one internally and then set the event as null externally it might remove it. I'm just hypothesising though I can't say for sure.
 
There are a couple of reasons that I can think of. First of all, overriding allows you to consume less resources. No extra objects are created (delegates/multicast delegates), no check for a null delegate must be made before invocation (this is done implicitly in VB and should be done explicitly in C#). Another reason is that events can be manipulated in ways that v-tables (the mechanism used for choosing a function from a list of overrides) can't. For instance, if I can get access to your MouseMove method (even private members can be accessed via reflection) I can detach it from the event. Cags had the right idea here.

Of course, if you want to do something like use the same method to handle multiple events, there is no great reason why you shouldn't use a single event handler instead of multiple overrides. Overrides are just the method that is generally preferred. (Yet, ironically, the designer handles events of the declaring class via event handlers instead of overrides.)
 
Last edited:
Back
Top