Export (0) Print
Expand All

Performing 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 .NET, 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:

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

PictureBox1.Refresh()   ' Forces a repaint of the control
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?", _
                       MessageBoxButtons.YesNo Or MsgBoxStyle.Question, _
                       "My Application")

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

Dim MyStr As String = "Some String"
'   Displays "String length is : 11
MsgBox("String length is : " & Len(MyStr))

See Also

The Basics of Working with Objects | Relation of Objects to Each Other | Setting and Retrieving Properties | Creating and Using Objects

© 2015 Microsoft