Visual Basic 2010 (Console) Guide
Parameters

Both procedures and functions can have parameters. Parameters are the information that is passed to the function or procedure.

There are two ways to pass parameters,

  • By Value
  • By Reference

In our examples so far, we have only used parameters which have been passed by value.

By Value

By default, procedure and function parameters are passed by value. This means that the values of the variables are used by the procedure, but not the variables themselves. Within the procedure, the parameters are local variables that have no effect on any global variables with the same name.

By Reference

If the keyword ByRef is used in the procedure definition, a reference to the variable is passed to the procedure. Any changes to the value of the variable within the procedure affects the global variable that was passed to it. Instead of telling the procedure what the value of the variable is, the program passes a reference to the location in memory where the variable is stored and the variable itself is altered.

Example Program

The following program contains parameters passed by value and parameters passed by reference.

Dim a As Integer
Dim b As Integer

Sub Main()
   a = 3
   b = 5
   cubeVal(a, b)
   Console.WriteLine("Value of a in Main: {0}", a)
   Console.WriteLine("Value of b in Main: {0}", b)
   cubeRef(a, b)
   Console.WriteLine("Value of a in Main: {0}", a)
   Console.WriteLine("Value of b in Main: {0}", b)
   Console.ReadLine()
End Sub

Sub cubeVal(ByVal a As Integer, ByVal b As Integer)
   a = a * a * a
   b = b * b * b
   Console.WriteLine("Value of a in procedure (ByVal): {0}", a)
   Console.WriteLine("Value of b in procedure (ByVal): {0}", b)
End Sub

Sub cubeRef(ByRef x As Integer, ByRef y As Integer)
   x = x * x * x
   y = y * y * y
   Console.WriteLine("Value of a in procedure (ByRef): {0}", a)
   Console.WriteLine("Value of b in procedure (ByRef): {0}", b)
End Sub

This program produces the following output,

Value of a in procedure (ByVal): 27
Value of b in procedure (ByVal): 125
Value of a in Main: 3
Value of b in Main: 5
Value of a in procedure (ByRef): 27
Value of b in procedure (ByRef): 125
Value of a in Main: 27
Value of b in Main: 125

The first two lines show the values that a and b have in the cubeVal procedure, where parameters are passed by value. The next two lines are produced after the cubeVal procedure has been executed and show that the global variables a and b have not changed their values.

When the cubeRef procedure is called, any change to the parameters (x and y in this case) is a change to the global variable to which these parameters refer. When the two variables are output after this procedure has been executed, the values of the global variables a and b have altered.