Method Arguments

The behavior of a class is defined by the methods of that class. To make your methods as flexible as possible, you can define parameters: information passed into the method when the method is invoked. Thus, rather than having to write one method when you want to sort your ListBox from A-Z and a second method when you want to sort it from Z-A, you define a more general Sort( ) method and pass in a parameter specifiying the order of the sort.

Methods can take any number of parameters.[10] The parameter list follows the method name and is enclosed in parentheses. Each parameter’s type is identified along with the name of the parameter using the As keyword.

For example, the following declaration defines a sub procedure (thus, it returns no value) named MyMethod( ) which takes two parameters, an integer and a button:

Sub MyMethod (firstParam As Integer, secondParam As Button)
  ' ...
End Sub

Within the body of the method, the parameters act as local variables, as if you had declared them in the body of the method and initialized them with the values passed in. Example 5-4 illustrates how you pass values into a method, in this case values of type Integer and Single.

Note

The Visual Studio .NET editor will mark your parameters as ByVal, indicating that the parameter is passed “by value.”

                  ByVal firstParam As Integer

When a parameter is passed by value, a copy is made. This is as opposed to passing “by reference.” The ByVal keyword and its implications are discussed later ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.