JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Functions

Unlike Sub procedures (see the previous topic), functions can return values, as discussed in the In Depth section of this chapter. You use the Function statement to create a function:

[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable |
MustOverride | Shadows | Shared }]
[{ Public | Protected | Friend | Protected Friend | Private }] Function
name[(arglist)] [ As type ]
   [ statements ]
   [ Exit Function ]
   [ statements ]
End Function

When you use ByVal (the default in VB .NET), you pass a copy of a variable to a procedure; when you use ByRef, you pass a reference to the variable, and if you make changes to that reference, the original variable is changed.

The various parts of this statement are the same as for Sub procedures (see the previous topic) except for the As type clause, which specifies the type of the return value from the function; here's how to set the type item:

  • type-This is optional unless Option Strict is On. Data type of the value returned by the Function procedure can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, or String; or the name of an enumeration, structure, class, or interface.


If you use Exit Function without assigning a value to name, the function returns the default value appropriate to argtype. This is 0 for Byte, Char, Decimal, Double, Integer, Long, Short, and Single; Nothing for Object, String, and all arrays; False for Boolean; and #1/1/0001 12:00 AM# for Date.

The Return statement simultaneously assigns the return value and exits the function; any number of Return statements can appear anywhere in the procedure. (You also can mix Exit Function and Return statements.) Here's an example function-Addem-we saw in the In Depth section of this chapter, which adds two integer values passed to it:

Module Module1
    Sub Main()
        Dim intValue As Integer = 2
        System.Console.WriteLine("{0}+{1}={2}", _
            intValue, intValue, Addem(intValue, intValue))
    End Sub

    Function Addem(ByVal int1 As Integer, ByVal int2 As Integer) As Long
        Return int1 + int2
    End Function
End Module
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor