|Me, Myself and I - Objects VB style|
|Written by Mike James|
|Tuesday, 29 June 2010|
Page 1 of 2
Visual Basic has an interesting approach to objects. We look into the inner workings of Me, My, MyBase and MyClass.
Me, Myself and I - Objects VB style
Visual Basic .NET hasn’t simply followed the way that the rest of the world does objects.
It has adapted and added facilities, presumably initially to make the transition from partial to complete object orientation easier to understand for existing VB 6 programmers.
However if you are familiar with the more generaly existing terminology its approach may cause some confusion
If this wasn’t enough innovation, VB also adds some interesting but possibly confusing “pronouns” to the mix. This article looks at why there is a proliferation of “pronouns”, Me, My, MyClass and MyBase, in VB?
The one to dispose of first is “My” which fairly trivial because it is just the prefix used for the My classes such as MyComputer etc.
In other words it has nothing to do with object-oriented facilities and you can ignore it from this point of view.
Notice, however, that the My classes are like the Form class and are “class instances” which can be used without instantiation, i.e. we have a confusion between class and instance.
It is also worth knowing that the My classes can be used in C# or any .NET language. All you have to do is load a reference to Microsoft.VisualBasic and add:
After this you can instantiate instances of all of the My classes. For example:
Computer c = new Computer();
Notice that you can't use anything like the My object but it isn't difficult to create a wrapper that allows the classes to be used without instantiation.
The Me keyword plays the role of “this” in C# and refers to the currently running instance.
That is, within a class definition Me.Show calls the current instance’s Show method. The Me keyword takes account of any virtual overriding that you may have but not any non-virtual overriding you might have implemented.
For example, if we define to classes:
Public Class Class1
Overridable Sub MethodB()
Public Class Class2
Overrides Sub MethodB()
Then MethodB is virtual and the result of:
Dim C1 As Class1
is that Class2’s MethodA calls Class2’s new definition of MethodB. even though the compiler can’t know what this is at compile time. If you change Class2’s MethodB to Shadows, i.e. non-virtual, then it is Class1’s MethodB that is called by Class2’s MethodA.
|Last Updated ( Tuesday, 29 June 2010 )|