Functions


Functions are basically the same as subroutines, except that they return some sort of value. The syntax for defining a function is as follows:

  [attribute_list] [inheritance_mode] [accessibility] _ Function function_name([parameters]) [As return_type] [ Implements interface.function ]     [ statements ] End Function 

This is almost the same as the syntax for defining a subroutine. See the section, “Subroutines,” earlier in this chapter for information about most of this declaration’s clauses.

One difference is that a function ends with the End Function statement rather than End Sub. Similarly a function can exit before reaching its end using Exit Function rather than Exit Sub.

The one really new piece in the declaration is the clause As return_type that comes after the function’s parameter list. This tells Visual Basic the type of value that the function will return.

The function can set its return value in one of two ways. First, it can set its name equal to the value it wants to return. The Factorial function shown in the following code calculates the factorial of a number. Written N!, the factorial of N is N * (N - 1) * (N - 2) . . . * 1. The function initializes its result variable to 1, and then loops over the values between 1 and the number parameter, multiplying these values to the result. It finishes by setting its name, Factorial, equal to the result value that it should return.

  Private Function Factorial(ByVal number As Integer) As Double     Dim result As Double = 1     For i As Integer = 2 To number         result *= i     Next i     Factorial = result End Function 

A function can assign and reassign its return value as many times as it wants to before it returns. Whatever value is assigned last becomes the function’s return value.

The second way a function can assign its return value is to use the Return keyword followed by the value that the function should return. The following code shows the Factorial function rewritten to use the Return statement:

  Private Function Factorial(ByVal number As Integer) As Double     Dim result As Double = 1     For i As Integer = 2 To number         result *= i     Next i     Return result End Function  

The Return statement is roughly equivalent to setting the function’s name equal to the return value, and then immediately using an Exit Function statement. The Return statement may allow the compiler to perform extra optimizations, however, so it is generally preferred to setting the function’s name equal to the return value.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net