Visual Basic Language Reference  

Function Statement

Declares the name, arguments, and code that define a Function procedure.

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

Parts

attrlist
Optional. List of attributes that apply to this procedure. Multiple attributes are separated by commas.
Overloads
Optional. Indicates that this Function procedure overloads one or more procedures defined with the same name in a base class. The argument list in this declaration must be different from the argument list of every overloaded procedure. The lists must differ in the number of arguments, their data types, or both. This allows the compiler to distinguish which version to use.

You do not have to use the Overloads keyword when you are defining multiple overloaded procedures in the same class. However, if you use Overloads in one of the declarations, you must use it in all of them.

You cannot specify both Overloads and Shadows in the same procedure declaration.

Overrides
Optional. Indicates that this Function procedure overrides an identically named procedure in a base class. The number and data types of the arguments, and the data type of the return value, must exactly match those of the base class procedure.
Overridable
Optional. Indicates that this Function procedure can be overridden by an identically named procedure in a derived class. Overridable is the default setting for a procedure that itself overrides a base class procedure.
NotOverridable
Optional. Indicates that this Function procedure cannot be overridden in a derived class. NotOverridable is the default setting for a procedure that does not itself override a base class procedure.
MustOverride
Optional. Indicates that this Function procedure is not implemented in this class, and must be implemented in a derived class for that class to be creatable.
Shadows
Optional. Indicates that this Function procedure shadows an identically named programming element, or set of overloaded elements, in a base class. You can shadow any kind of declared element with any other kind. If you shadow a procedure with another procedure, the arguments and the return type do not have to match those in the base class procedure. A shadowed element is unavailable in the derived class that shadows it.

You cannot specify both Overloads and Shadows in the same procedure declaration.

Shared
Optional. Indicates that this Function procedure is a shared procedure. This means it is not associated with a specific instance of a class or structure. You can call a shared procedure by qualifying it either with the class or structure name, or with the variable name of a specific instance of the class or structure.
Public
Optional. Procedures declared with the Public keyword have public access. There are no restrictions on the accessibility of public procedures.
Protected
Optional. Procedures declared with the Protected keyword have protected access. They are accessible only from within their own class or from a derived class. Protected access can be specified only on members of classes. It is not a superset of friend access.
Friend
Optional. Procedures declared with the Friend keyword have friend access. They are accessible from within the program that contains their declaration and from anywhere else in the same assembly.
Protected Friend
Optional. Procedures declared with the Protected Friend keywords have the union of protected and friend access. They can be used by code in the same assembly, as well as by code in derived classes. Protected friend access can be specified only on members of classes.
Private
Optional. Procedures declared with the Private keyword have private access. They are accessible only from within their declaration context, including from members of any nested types such as procedures.
name
Required. Name of the Function procedure. Must be a valid Visual Basic identifier.
arglist
Optional. List of variables or expressions representing arguments that are passed to the Function procedure when it is called. Multiple arguments are separated by commas. If you supply an argument list, you must enclose it in parentheses.
type
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.
Implements
Optional. Indicates that this Function procedure implements a Function procedure defined by an interface.
interface
Required if Implements is supplied. The interface implemented by the class or structure containing this Function procedure. The class or structure must specify interface in an Implements statement immediately following the Class or Structure statement.
definedname
Required if Implements is supplied. The name by which the Function procedure is defined in interface. The name of this Function procedure (in name) does not have to be the same as definedname.
statements
Optional. A block of statements to be executed within the Function procedure.
End Function
Terminates the definition of this Function procedure.

Each argument in the arglist part has the following syntax and parts:

<attrlist> ] [ Optional ] [{ ByVal | ByRef }] [ ParamArray ] 
argname[( )] [ As argtype ] [ = defaultvalue ]

arglist Parts

attrlist
Optional. List of attributes that apply to this argument. Multiple attributes are separated by commas.
Optional
Optional. Indicates that this argument is not required when the procedure is called. If this keyword is used, all subsequent arguments in arglist must also be optional and be declared using the Optional keyword. Every optional argument declaration must supply the defaultvalue clause. Optional cannot be used for any argument if ParamArray is used.
ByVal
Optional. Indicates that the procedure cannot replace or reassign the underlying variable element in the calling code. However, if the argument is a reference type, the procedure can modify the contents or members of the underlying object. ByVal is the default in Visual Basic.
ByRef
Optional. Indicates that the procedure can modify the underlying variable in the calling code the same way the calling code itself can.
ParamArray
Optional. Used only as the last argument in arglist to indicate that the final argument is an optional array of elements of the specified type. The ParamArray keyword allows you to pass an arbitrary number of arguments to the procedure. A ParamArray argument is always passed using ByVal.
argname
Required. Name of the variable representing the argument. Must be a valid Visual Basic identifier.
argtype
Optional unless Option Strict is On. Data type of the argument passed to the 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.
defaultvalue
Required for Optional arguments. Any constant or constant expression that evaluates to the data type of the argument. If the type is Object; or a class, interface, array, or structure, the default value can only be Nothing.

Each attribute in the attrlist part has the following syntax and parts:

attrname [(attrargs | attrinit })]

attrlist Parts

attrname
Required. Name of the attribute. Must be a valid Visual Basic identifier.
attrargs
Optional. List of positional arguments for this attribute. Multiple arguments are separated by commas.
attrinit
Optional. List of field or property initializers for this attribute. Multiple initializers are separated by commas.

Remarks

All executable code must be in procedures. You can define a Function procedure inside a module, class, interface, or structure, but not inside another procedure.

Function procedures are Public by default. To specify a different accessibility, include Protected, Friend, Protected Friend, or Private in the declaration.

When the Function procedure returns to the calling program, execution continues with the statement following the statement that called it.

The Exit Function statement causes an immediate exit from a Function procedure. Any number of Exit Function statements can appear anywhere in the procedure.

To return a value from a function, you can either assign the value to the function name or include it in a Return statement. The following example assigns the return value to the function name MyFunction and then uses the Exit Function statement to return:

Function MyFunction(ByVal J As Integer) As Double
   ' ...
   MyFunction = 3.87
   ' ...
   Exit Function
   ' ...
End Function

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, as in the following example:

Function MyFunction(ByVal J As Integer) As Double
   ' ...
   Return 3.87
   ' ...
End Function

Any number of Return statements can appear anywhere in the procedure. You can also mix Exit Function and Return statements.

You can use a Function procedure on the right side of an expression when you want to use the value returned by the function. You use the Function procedure the same way you use any library function such as Sqrt, Cos, or ChrW.

You call a Function procedure by using the procedure name, followed by the argument list in parentheses, in an expression. You can omit the parentheses only if you are not supplying any arguments. A function can also be called using the Call statement, in which case the return value is ignored.

Note   Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

Example

This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. The last example uses hard-typed, initialized Optional arguments.

' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(ByVal NumberArg As Double) As Double
   If NumberArg < 0 Then   ' Evaluate argument.
      Exit Function   ' Exit to calling procedure.
   Else
      CalculateSquareRoot = Sqrt(NumberArg)   ' Return square root.
   End If
End Function

Using the ParamArray keyword enables a function to accept a variable number of arguments.

' If a function's arguments are defined as follows:
Function CalcSum(ByVal ParamArray Args() As Double) As Object
' The function can be invoked as follows:
Dim ReturnedValue As Object
ReturnedValue = CalcSum(4, 3, 2, 1)
' Local variables are assigned the following values:
' Args(0) = 4, Args(1) = 3, and so on.

Optional arguments can have default values and types, as long as the types are specified within the function.

' If a function's arguments are defined as follows:
Function MyFunc(MyStr As String, Optional MyArg1 As Integer = 5, _
                Optional MyArg2 As String = "Dolly") As Object
' The function can be invoked as follows:
Dim RetVal As Object
RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5) ' Second argument omitted.
' Arguments one and three passing arguments by name.
RetVal = MyFunc(MyStr:="Hello", MyArg2:="World")

See Also

Call Statement | Sub Statement | Dim Statement | Implements Statement