H o m e

 

T h e    V i s u a l    B a s i c    ‘ M e ’    K e y w o r d    

By Michael McIntyre

mikemc@getdotnetcode.com

 

This article provides some guidance for using the Visual Basic.NET ‘Me’ keyword.  As will be explained, there is no reason not to use ‘Me’ keyword and very good reasons to use ‘Me’. NOTE: This guidance also applies to the C# equivalent to ‘Me’ keyword, which is the ‘This’ keyword.

 

Me Is Required in Some Situations

 

Consider this code.

 

Public Class Customer

 

    ' LastName field.

    Private _LastName As String

 

    ' LastName property.

    Public Property LastName() As String

        Get

            Return _LastName

        End Get

        Set(ByVal Value As String)

            _LastName = Value

        End Set

    End Property

 

    ' Customer constructor method.

    Public Sub New(ByVal lastName As String)

        ' Without Me, assignment of lastName argument

        ' to LastName property can fail.

        Me.LastName = lastName

    End Sub

 

End Class

 

In the Public Sub New method, ‘Me’ is said to disambiguate between Sub New's lastName parameter and the Employee class’ LastName property. In other words, Me makes it clear that the value of the lastName argument passed into Sub New is to be assigned to the Employee class’ LastName property.  NOTE:  If you don't use Me in this case you may not get an exception, but assignments will not always work as expected.

 

Using Me Is An Object-Oriented Best Practic

 

Using Me triggers Intellisense that reinforces an object-oriented style of programming. Many authors and experts call Me - and the C# equivalent ‘This’ - the OOP syntax for referring to class members.

 

Me Improves Code Readability

 

Consider this code.

 

Public Class Form1

    Inherits System.Windows.Forms.Form

    Private salesTaxRate As Decimal

 

    Public Function GetSalesTax(ByVal saleAmount As Decimal) _

    As Decimal

        ' Declare a variable of type Decimal named salesTaxAmount.

        Dim salesTaxAmount As Decimal

        ' Calculate salesTaxAmount as saleAmount * salesTaxRate.

        salesTaxAmount = Me.salesTaxRate * saleAmount

        ' Return salesTaxAmount

        Return salesTaxAmount

    End Function

 

End Class

 

Using Me with salesTaxRate in the GetSalesTax method makes it more obvious that salesTaxRate is a class member not to be confused with any variables local to the method.  In more complex methods where many local variables are used with many class member fields Me can improve readability dramatically.

 

There Is No Penalty For Using ‘Me’

 

 Not a one.

 

Summary

 

Given the advantages and lack of any disadvantage, using Me is highly recommended.

 

Copyright © 2001-2004 aZ Software Developers. All rights reserved.