Using the Me Keyword for Self-Reference              
                         
Instance (non-shared) methods can only be invoked on an existing object. Within any instance method (including
constructors), you can refer to the current object using the
Me keyword. In fact, whenever you access another
instance member, you are implicitly using the
Me keyword. You cannot use “Me”, either explicitly or
implicitly, from within a shared member.


Public Class Employee

   Private mWage As Double
   Private mName As String
   Private mHours As Double

   Public Function ComputePay() As Double
      Dim pay As Double

      'Using implicit Me
      pay = mWage * mHours

      'The above line is the same as ...
      pay = Me.mWage * Me.mHours

      Return pay
   End Function

End Class


The Me keyword can be used to distinguish between class fields and incoming parameters or local variables. By
convention, we’ve prefixed each field name with “m” to indicate it is a class member. But some coding styles
don’t allow this convention. Consider the following employee class.


Public Class Employee

   'Class fields. Note: no m prefix.
   Private name As String
   Private wage As Double  
   Private hours As Double

   Public Sub New(name As String, wage As Double, hours as Double)
      'Use Me to distinguish between class fields and params
      Me.name = name
      Me.wage = wage
      Me.hours = hours
   End Sub
End Class


You can also use the Me keyword to force one constructor to call another. This can be helpful when you wish
to designate a ‘master’ constructor to do all parameter validation, field assignment, etc. The ‘master’ constructor
will typically be the constructor with the greatest number of arguments. The other constructors can forward to
the master, specifying any missing information. In this way, you only need to modify 1 constructor should
your business rules change.


Public Class Employee

   Private name As String
   Private wage As Double  
   Private hours As Double

   'If the user calls this ctor, forward to the 3-arg ctor.

   Public Sub New(name As String)
      Me.New(name, 0.0, 0.0)
   End Sub

   Public Sub New(name As String, wage As Double, hours as Double)

      'Use Me to distinguish between class fields and params

      Me.name = name
      Me.wage = wage
      Me.hours = hours
   End Sub
End Class
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Me Keyword
Table of Contents
Courseware
Training Resources
Tutorials
Services