Me, Myself and I - Objects VB style
Me, Myself and I - Objects VB style
Written by Mike James   
Tuesday, 29 June 2010
Article Index
Me, Myself and I - Objects VB style
MyBase and MyClass


MyBase and MyClass

The two “pronouns” that might cause confusion are MyBase and MyClass.

MyBase is a reference to the base class of the derived class.

MyClass on the other hand is a reference to the class of the current instance just like Me but in this case the class as originally implemented – i.e. it ignores any virtual inheritance you may have attempted.

I have to admit that to construct an example that shows the difference between Me and MyClass isn’t easy and the result is a coding style you should avoid.

The simplest example I can offer changes the previous Class1 Method1 to:

Sub MethodA()
End Sub

Now if MethodB is non-virtual then Me and MyClass both call Class1’s MethodB. If it is virtual then Me calls Class2’s MethodB and MyClass calls Class1’s. 


If you think you are getting the idea try the following example :

Public Class Class1
Overridable Sub MethodA()
MsgBox("Method A Class1 called")
End Sub
 Overridable Sub MethodB()
MsgBox("Method B Class1 called")
End Sub
End Class
Public Class Class2
Inherits Class1
Overrides Sub MethodA()
MsgBox("Method A Class2 called")
End Sub

Overrides Sub MethodB()
MsgBox("Method B Class2 called")
End Sub
End Class

Notice that Class2’s MethodA now calls MethodA of the base class, which is a fairly common way of extending an existing method. Also notice that Class2’s MethodB overrides Class1’s MethodB. To see the difference we need to use late binding again as in:

Dim C1 As Class1
C1 = New Class2

Now when MethodA is called it is Class2’s MethodA because the binding is based on run time type, i.e. it is a virtual method. But when Class2’s MethodA calls the base class, i.e. Class1’s, MethodA you will discover that the calls to MethodB are treated differently. In this case the Me.MethodB() call resolves to Class2’s MethodB as the instance is of type Class2 and Me honours virtual overrides.   However, MyClass.MethodB() resolves to Class1’s MethodB because the compile time type of the reference is Class1 and MyClass doesn’t honour virtual overrides.

If you have a headache I can’t say I blame you. I’d rather avoid this sort of construction.

Use MyClass to ensure that a method call is to the declared type of the variable irrespective of the type of the instance that is assigned to it at run time.







Last Updated ( Tuesday, 29 June 2010 )

RSS feed of all content
I Programmer - full contents
Copyright © 2015 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.