tags:

views:

284

answers:

4

In what scenarios would one use the mybase and myclass kewordsin vb .net?

+5  A: 

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

Konrad Rudolph
+2  A: 

Both are used when you need to call an virtual method and you need to specify which one. MyBase will call the method in the base class, MyClass will call the method in the current class.

I don't think I've used MyClass more than once or twice, but MyBase I've used quite a bit when I override a method but want the code in the overridden method to be executed as well.

MyBase:

http://msdn.microsoft.com/en-us/library/dzfhkk01%28VS.71%29.aspx

MyClass:

http://msdn.microsoft.com/en-us/library/b3b35kyk%28VS.71%29.aspx

ho1
+1  A: 

mybase refers to the immediate base class of the current instance.

myclass refers to the current instance, but ignores any overridden implementation of the properties/methods of the class.

In a nutshell the overall usage of both is for Polymorphism. Here is a nice article which explains the keywords a little further.

James
A: 

These keywords are used in scenarios involving Inheritence. MyBase, MyClass are often used to refer to some functionality or property in the parent class. If you have a class that derives from another, those keywords are used to reference code in the context of the parent class.

Achilles