Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"MyBase" and "MyClass" Usage in VB.NET

Tags:

vb.net

In what scenarios would one use the MyBase and MyClass keywords in VB.NET?

like image 562
Nehil Verma Avatar asked May 17 '10 13:05

Nehil Verma


People also ask

What is the use for MyBase 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.

What is use of Me keyword in VB net?

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.


1 Answers

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

like image 168
Konrad Rudolph Avatar answered Sep 27 '22 20:09

Konrad Rudolph