Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

Is there any practical difference between the two procedures in the following class?

 

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?

Edited by rbulph
Posted
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.
Anybody looking for a graduate programmer (Midlands, England)?
  • Leaders
Posted (edited)

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.)

Edited by snarfblam
[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...