How to: Perform Actions with MethodsĀ 

Methods are procedures associated with objects. Unlike fields and properties, which represent information an object can store, methods represent actions that an object can perform. Methods can affect the values of properties. For example, to use a radio analogy, you can employ a SetVolume method to change the value of a Volume property. Similarly, in Visual Basic, the items of list boxes have a List property, which you can change with the Clear and Add methods.

When you use a method in code, the way you write the statement depends on how many arguments the method requires and whether it returns a value. Generally, you use methods just like you use subroutines or function calls. More specifically, you invoke methods in the same way as module procedures, except that you can qualify methods with an expression specifying the object instance whose method is to be called. When unqualified, the instance is implicitly the Me variable.

To use a method that does not require arguments

  • Use the following syntax:

    Object.method()

    In the following example, the Refresh method repaints the picture box:

    ' Force the control to repaint.
    PictureBox1.Refresh()
    

    Note

    Some methods, such as Refresh, do not have arguments and do not return values.

To use a method that requires multiple arguments

  • Place the arguments in parentheses and separate them with commas. In the following example, the MsgBox method uses arguments that specify the message to display and the style of the message box:

    MsgBox("Database update complete", _
           MsgBoxStyle.OKOnly Or MsgBoxStyle.Exclamation, _
           "My Application")
    

To use a method that returns a value

  • Assign the return value to a variable, or directly use the method call as a parameter to another call. The following code stores the return value:

    Dim Response As MsgBoxResult
    Response = MsgBox("Do you want to exit?", _
                       MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _
                       "My Application")
    

    This example uses the value returned from the Len method as an argument to MsgBox.

    Dim TestStr As String = "Some String"
    ' Display the string "String length is : 11".
    MsgBox("String length is : " & Len(TestStr))
    

See Also

Tasks

How to: Set and Retrieve Properties

Concepts

Relationships Among Objects

Other Resources

Creating and Using Objects