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 by using Exit Function rather than Exit Sub.

The one nontrivial difference between subroutine and function declarations 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 returns.

The function can set its return value in one of two ways. First, it can set its own name equal to the value that it should return. The Factorial function shown in the following code calculates the factorial of a number. Written N!, the factorial of N is N * (N1) * (N2) . . .* 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(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(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. (Return is also the more modern syntax and has become so common that some developers don’t even recognize the other syntax anymore.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.250