Visual Basic Me Keyword

In visual basic, Me keyword is useful to refer the current instance of the class and by using Me keyword we can pass the current instance of the class as a parameter to the other methods.

 

In case, if the class contains parameters and variables with the same name, then Me keyword is useful to distinguish between the parameters and variables.

 

We can also use Me keyword to declare the indexers and to specify the instance variable in the parameter list of an extension method.

Visual Basic Me Keyword Syntax

Following is the syntax of using Me keyword in visual basic programming language.

 

Me.instance_variable

If you observe the above syntax, Me is a keyword and instance_variable is an instance variable name.

Visual Basic Me keyword Example

Following is the example of using Me keyword in a visual basic programming language to refer the class variables and parameters of the same name. We can also use Me keyword to send the instance of a class to the method of another class.

 

Module Module1

    Class User

        Public name, location As String

        Public marks As Long = 470

        Public Sub New(ByVal name As String, ByVal location As String)

            ' Use Me to distinguish between parameters and variables

            Me.name = name

            Me.location = location

        End Sub

        Public Sub GetUserDetails()

            Console.WriteLine("Name: {0}", name)

            Console.WriteLine("Location: {0}", location)

            ' Passing a class instance to the method using this

            Console.WriteLine("Marks: {0}", Exams.GetPercentage(Me))

        End Sub

    End Class

    Class Exams

        Public Shared Function GetPercentage(ByVal u As User) As Double

            Dim i As Double = (CDbl(470) / 600) * 100

            Return (i)

        End Function

    End Class

    Sub Main()

        Dim u As User = New User("Suresh Dasari", "Hyderabad")

        u.GetUserDetails()

        Console.WriteLine("Press Enter Key to Exit..")

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used Me keyword to distinguish between the class variables & parameters of same name and we used Me keyword to send the instance of class (User) to the method of another class.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Me keyword Example Result

 

This is how we can use Me keyword in a visual basic programming language to refer the instance of a class based on our requirements.