In what scenarios would one use the MyBase
and MyClass
keywords in VB.NET?
MyBase is commonly used to access base class members that are overridden or shadowed in a derived class. MyBase. New is used to explicitly call a base class constructor from a derived class constructor.
The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing. Me behaves like either an object variable or a structure variable referring to the current instance.
MyBase
is used when a virtual function needs to call its parent’s version. For example, consider:
Class Button
Public Overridable Sub Paint()
' Paint button here. '
End Sub
End Class
Class ButtonWithFancyBanner
Inherits Button
Public Overrides Sub Paint()
' First, paint the button. '
MyBase.Paint()
' Now, paint the banner. … '
End Sub
End Class
(This is the same as base
in C#.)
MyClass
is rarely used at all. It calls the own class’s method, even if it would usually call the derived class’s virtual method. In other words, it disbands the virtual method dispatching and instead makes a static call.
This is a contrived example. I’m hard-pressed to find a real-world usage now (although that certainly exists):
Class Base
Public Overridable Sub PrintName()
Console.WriteLine("I’m Base")
End Sub
Public Sub ReallyPrintMyName()
MyClass.PrintName()
End Sub
End Class
Class Derived
Inherits Base
Public Overrides Sub PrintName()
Console.WriteLine("I’m Derived")
End Sub
End Class
' … Usage: '
Dim b As Base = New Derived()
b.PrintName() ' Prints "I’m Derived" '
b.ReallyPrintMyName() ' Prints "I’m Base" '
(This doesn’t exist in C#. In IL, this issues a call
instead of the usual callvirt
opcode.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With