MyClass Keyword


MyClass Keyword

Syntax

     MyClass 

Description

The MyClass keyword provides a reference to the class in which the keyword is used.

Usage at a Glance

  • When using MyClass (as opposed to Me) to qualify a method invocation, as in:

         MyClass.IncSalary(  ) 

    the method is treated as if declared using the NotOverridable keyword. Regardless of the type of the object at runtime, the method called is the one declared in the class containing this statement (and not in any derived classes). The upcoming example illustrates this difference between MyClass and Me.

  • MyClass cannot be used with shared members.

Example

The following code defines a base class and a derived class, each of which has an IncSalary method.

     Public Class BaseClass        Public Overridable Function SuperSize _              (ByVal startValue As Long) As Long           ' ----- Double it!           Return startValue * 2        End Function        Public Sub ShowSuperSize(ByVal startValue As Long)           MsgBox(Me.SuperSize(startValue))           MsgBox(MyClass.SuperSize(startValue))        End Sub     End Class     Public Class DerivedClass        Inherits BaseClass        Public Overrides Function SuperSize _              (ByVal startValue As Long) As Long           ' ----- Triple it!           Return startValue * 3        End Function     End Class 

Consider the following code, placed in a form module:

     Dim testWithBase As New BaseClass(  )     Dim testWithDerived As New DerivedClass(  )     Dim pointToTest As BaseClass     pointToTest = testWithBase     pointToTest.ShowSuperSize(100)  ' Shows 200, 200     pointToTest = testWithDerived     pointToTest.ShowSuperSize(100)  ' Shows 300, 200 

The first call to ShowSuperSize is made using a variable of type BaseClass that refers to an object of type BaseClass. In this case, both calls:

     Me.ShowSuperSize     MyClass.ShowSuperSize 

return the same value, because they both call BaseClass.SuperSize.

However, in the second case, the variable of type BaseClass holds a reference to an object of type DerivedClass. In this case, Me refers to an object of type DerivedClass, whereas MyClass still refers to BaseClass. So the statement:

     Me.ShowSuperSize(100) 

returns 300, while:

     MyClass.ShowSuperSize(100) 

returns 200.

Version Differences

The My Class keyword is new to VB under .NET.

See Also

Me Keyword, MyBase Keyword




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net