VB.NET Functions

In VB.NET, the function is a separate group of codes that are used to perform a specific task when the defined function is called in a program. After the execution of a function, control transfer to the main() method for further execution. It returns a value. In VB.NET, we can create more than one function in a program to perform various functionalities. The function is also useful to code reusability by reducing the duplicity of the code. For example, if we need to use the same functionality at multiple places in a program, we can simply create a function and call it whenever required.

Defining a Function

The syntax to define a function is:

Where,

  • Access_Specifier: It defines the access level of the function such as public, private, or friend, Protected function to access the method.
  • Function_Name: The function_name indicate the name of the function that should be unique.
  • ParameterList: It defines the list of the parameters to send or retrieve data from a method.
  • Return_Type: It defines the data type of the variable that returns by the function.

The following are the various ways to define the function in a VB.NET.

Example: Write a program to find the sum and subtraction of two numbers using the function.

Find_Sum.vb

Output:

VB.NET Functions

In the above example, we have defined a SumOfTwo() and SubtractionOfTwo() function to add and subtract two predefined numbers. When the functions are called in the main() method, each function is executed and returns the sum and subtraction of two numbers, respectively.

Example: Write a program to reverse a number and check whether the given number is palindrome or not.

Palindrome.vb

Output:

VB.NET Functions

Recursive Function

When a function calls itself until the defined condition is satisfied, it is known as a recursive function. A recursive function is useful for solving many mathematical tasks such as generating the Fibonacci series, the factorial of a number, etc.

Let's create a program to calculate the factorial of a number using the recursive function.

Factorial_function.vb

Output:

VB.NET Functions

Passing Array as a Parameter

Let's create a program that parses an array as a pass parameters in a function.

Array_Parameter.vb

Output:

VB.NET Functions
Next TopicVB.NET Sub