Functions in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes Functions in Visual Basic .NET
By definition, a Visual Basic Function is chunk of code enclosed by the Function and End Function.
It performs a task for the code that invokes it and then returns some value.
Meaning, they are basically the same as subroutines, except that they return some sort of value.
Its syntax is as follows:
[ accessibility ] Function function_name [ paramaters ] [As return_type ] statements End FunctionThe accessibility can be Public, Protected, Friend, Protected Friend, or Private and determines which pieces of code can invoke the function.
The name of the function must be a valid Visual Basic identifier and should begin with a letter or an underscore.
The parameters are declared similarly to how you declare variables specifying passing mechanism, name, datatype and if the parameter is optional.
The passing mechanism determines the interaction between the element's data type and the passing mechanism.
If you include ByVal keyword in the declaration, the function makes own local copy of the parameter and then can modify this value without affecting the value of the original parameter.
If you include ByRef keyword in the declaration, the function does not create a separate copy of the parameter variable.
Instead, it uses a reference to the original parameter passed into the subroutine and any changes the function makes to the value are reflected in the calling function as well.
To declare an optional parameter you use Optional keyword, so the code that uses it may omit that parameter.
Private Function GetValue(Optional ByVal entry As String = "") As String Return entry End Function
The function can set its return value either by setting its name equal to the value it wants to return, or by using the Return keyword followed by the value that the function should return.
Private Function GetValue(Optional ByVal entry As String = "") As String Dim result As String = String.Empty If entry = "" Then result = "No value found" Else result = entry End If GetValue = result End FunctionOR
Private Function GetValue(Optional ByVal entry As String = "") As String Dim result As String = String.Empty If entry = "" Then result = "No value found" Else result = entry End If Return result End Function
Most importantly the functions allow you to extract code that you may need to use under more than one circumstance and place it in one location where you can call it as needed:
Private Function CubeVolume(ByVal x As Double) As Double Dim result As Double = 0 result = x * x * x Return result End FunctionThen whenever you want to calculate the cube volume you simply call the CubeVolume with side of the cube as parameter provided e.g.
Console.WriteLine("The volume of the cube is: " & CubeVolume(5))Previous Lesson | Next Lesson