Académique Documents
Professionnel Documents
Culture Documents
For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.
Declares the name, parameters, and code that define a Function procedure.
Syntax
[<attributelist>][accessmodifier][proceduremodifiers][Shared][Shadows][Async|Iterator]
Functionname[(Oftypeparamlist)][(parameterlist)][Asreturntype][Implementsimplementslist|Handleseventlist]
[statements]
[ExitFunction]
[statements]
EndFunction
Parts
attributelist
accessmodifier
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 1/10
1/25/2017 FunctionStatement(VisualBasic)
Public
Protected
Friend
Private
ProtectedFriend
proceduremodifiers
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverrideOverrides
NotOverridableOverrides
Shared
Shadows
Async
Iterator
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 2/10
1/25/2017 FunctionStatement(VisualBasic)
name
typeparamlist
Optional. List of type parameters for a generic procedure. See Type List.
parameterlist
Optional. List of local variable names representing the parameters of this procedure. See Parameter List.
returntype
Required if OptionStrict is On. Data type of the value returned by this procedure.
Implements
Optional. Indicates that this procedure implements one or more Function procedures, each one defined in an interface implemented by this procedure's
containing class or structure. See Implements Statement.
implementslist
implementedprocedure[,implementedprocedure...]
interface.definedname
Part Description
interface Required. Name of an interface implemented by this procedure's containing class or structure.
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 3/10
1/25/2017 FunctionStatement(VisualBasic)
Handles
Optional. Indicates that this procedure can handle one or more specific events. See Handles.
eventlist
eventspecifier[,eventspecifier...]
eventvariable.event
Part Description
eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.
statements
EndFunction
Remarks
All executable code must be inside a procedure. Each procedure, in turn, is declared within a class, a structure, or a module that is referred to as the containing class,
structure, or module.
To return a value to the calling code, use a Function procedure; otherwise, use a Sub procedure.
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 4/10
1/25/2017 FunctionStatement(VisualBasic)
Defining a Function
You can define a Function procedure only at the module level. Therefore, the declaration context for a function must be a class, a structure, a module, or an interface and
can't be a source file, a namespace, a procedure, or a block. For more information, see Declaration Contexts and Default Access Levels.
Function procedures default to public access. You can adjust their access levels with the access modifiers.
A Function procedure can declare the data type of the value that the procedure returns. You can specify any data type or the name of an enumeration, a structure, a class,
or an interface. If you don't specify the returntype parameter, the procedure returns Object.
If this procedure uses the Implements keyword, the containing class or structure must also have an Implements statement that immediately follows its Class or
Structure statement. The Implements statement must include each interface that's specified in implementslist. However, the name by which an interface defines the
Function in definedname doesn't need to match the name of this procedure in name.
Note
You can use lambda expressions to define function expressions inline. For more information, see Function Expression and Lambda Expressions.
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 Return statement simultaneously assigns the return value and exits the function, as the following example shows.
VB
FunctionmyFunction(ByValjAsInteger)AsDouble
Return3.87*j
EndFunction
The following example assigns the return value to the function name myFunction and then uses the ExitFunction statement to return.
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 5/10
1/25/2017 FunctionStatement(VisualBasic)
VB
FunctionmyFunction(ByValjAsInteger)AsDouble
myFunction=3.87*j
ExitFunction
EndFunction
The ExitFunction and Return statements cause an immediate exit from a Function procedure. Any number of ExitFunction and Return statements can appear
anywhere in the procedure, and you can mix ExitFunction and Return statements.
If you use ExitFunction without assigning a value to name, the procedure returns the default value for the data type that's specified in returntype. If returntype isn't
specified, the procedure returns Nothing, which is the default value for Object.
Calling a Function
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
aren't supplying any arguments. However, your code is more readable if you always include the parentheses.
You call a Function procedure the same way that you call any library function such as Sqrt, Cos, or ChrW.
You can also call a function by using the Call keyword. In that case, the return value is ignored. Use of the Call keyword isn't recommended in most cases. For more
information, see Call Statement.
Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, you shouldn't use a Function procedure in an arithmetic
expression when the function changes the value of variables in the same expression.
Async Functions
The Async feature allows you to invoke asynchronous functions without using explicit callbacks or manually splitting your code across multiple functions or lambda
expressions.
If you mark a function with the Async modifier, you can use the Await operator in the function. When control reaches an Await expression in the Async function, control
returns to the caller, and progress in the function is suspended until the awaited task completes. When the task is complete, execution can resume in the function.
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 6/10
1/25/2017 FunctionStatement(VisualBasic)
Note
An Async procedure returns to the caller when either it encounters the first awaited object thats not yet complete, or it gets to the end of the Async procedure,
whichever occurs first.
An Async function can have a return type of Task<TResult> or Task. An example of an Async function that has a return type of Task<TResult> is provided below.
A Sub Statement can also be marked with the Async modifier. This is primarily used for event handlers, where a value cannot be returned. An Async``Sub procedure can't
be awaited, and the caller of an Async``Sub procedure can't catch exceptions that are thrown by the Sub procedure.
For more information about Async functions, see Asynchronous Programming with Async and Await, Control Flow in Async Programs, and Async Return Types.
Iterator Functions
An iterator function performs a custom iteration over a collection, such as a list or array. An iterator function uses the Yield statement to return each element one at a time.
When a Yield statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.
You call an iterator from client code by using a For EachNext statement.
The return type of an iterator function can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
Example
The following example uses the Function statement to declare the name, parameters, and code that form the body of a Function procedure. The ParamArray modifier
enables the function to accept a variable number of arguments.
VB
PublicFunctioncalcSum(ByValParamArrayargs()AsDouble)AsDouble
calcSum=0
Ifargs.Length<=0ThenExitFunction
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 7/10
1/25/2017 FunctionStatement(VisualBasic)
ForiAsInteger=0ToUBound(args,1)
calcSum+=args(i)
Nexti
EndFunction
Example
The following example invokes the function declared in the preceding example.
VB
ModuleModule1
SubMain()
'Inthefollowingfunctioncall,calcSum'slocalvariables
'areassignedthefollowingvalues:args(0)=4,args(1)=3,
'andsoon.Thedisplayedsumis10.
DimreturnedValueAsDouble=calcSum(4,3,2,1)
Console.WriteLine("Sum:"&returnedValue)
'Parameterargsacceptszeroormorearguments.Thesum
'displayedbythefollowingstatementsis0.
returnedValue=calcSum()
Console.WriteLine("Sum:"&returnedValue)
EndSub
PublicFunctioncalcSum(ByValParamArrayargs()AsDouble)AsDouble
calcSum=0
Ifargs.Length<=0ThenExitFunction
ForiAsInteger=0ToUBound(args,1)
calcSum+=args(i)
Nexti
EndFunction
EndModule
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 8/10
1/25/2017 FunctionStatement(VisualBasic)
Example
In the following example, DelayAsync is an Async``Function that has a return type of Task<TResult>. DelayAsync has a Return statement that returns an integer.
Therefore the function declaration of DelayAsync needs to have a return type of Task(OfInteger). Because the return type is Task(OfInteger), the evaluation of the
Await expression in DoSomethingAsync produces an integer. This is demonstrated in this statement: DimresultAsInteger=AwaitdelayTask.
The startButton_Click procedure is an example of an AsyncSub procedure. Because DoSomethingAsync is an Async function, the task for the call to
DoSomethingAsync must be awaited, as the following statement demonstrates: AwaitDoSomethingAsync(). The startButton_Click``Sub procedure must be defined
with the Async modifier because it has an Await expression.
VB
'ImportsSystem.Diagnostics
'ImportsSystem.Threading.Tasks
'ThisClickeventismarkedwiththeAsyncmodifier.
PrivateAsyncSubstartButton_Click(senderAsObject,eAsRoutedEventArgs)HandlesstartButton.Click
AwaitDoSomethingAsync()
EndSub
PrivateAsyncFunctionDoSomethingAsync()AsTask
DimdelayTaskAsTask(OfInteger)=DelayAsync()
DimresultAsInteger=AwaitdelayTask
'Theprevioustwostatementsmaybecombinedinto
'thefollowingstatement.
'DimresultAsInteger=AwaitDelayAsync()
Debug.WriteLine("Result:"&result)
EndFunction
PrivateAsyncFunctionDelayAsync()AsTask(OfInteger)
AwaitTask.Delay(100)
Return5
EndFunction
'Output:
'Result:5
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 9/10
1/25/2017 FunctionStatement(VisualBasic)
See Also
Sub Statement
Function Procedures
Parameter List
Dim Statement
Call Statement
Of
Parameter Arrays
How to: Use a Generic Class
Troubleshooting Procedures
Lambda Expressions
Function Expression
2017 Microsoft
https://msdn.microsoft.com/enus/library/sect4ck6.aspx 10/10