VB.Net program to demonstrate the optional parameter in the function

Here, we are going to demonstrate the optional parameter in the function in VB.Net.
Submitted by Nidhi, on December 13, 2020 [Last updated : March 07, 2023]

Optional parameter in VB.Net function

Here, we will create a user define sub-routine that will accept three arguments, here we will use two optional arguments. The optional parameter contains a default value. If we will not pass the value for optional parameters then it will use the default value.

Program/Source Code:

The source code to demonstrate the optional parameter in the function is given below. The given program is compiled and executed successfully.

VB.Net code to demonstrate the example of optional parameter in the function

'VB.Net program to demonstrate the optional parameter in the function.
Module Module1

    Function AddNum(ByVal num1 As Integer, Optional ByVal num2 As Integer = 20, Optional ByVal num3 As Integer = 30) As Integer
        Dim result As Integer = 0

        result = num1 + num2 + num3
        AddNum = result

    End Function

    Sub Main()
        Dim result As Integer = 0
        
        result = AddNum(10)
        Console.WriteLine("Addition is: {0}", result)

        result = AddNum(10, 40)
        Console.WriteLine("Addition is: {0}", result)

        result = AddNum(10, 40, 60)
        Console.WriteLine("Addition is: {0}", result)

    End Sub
End Module

Output

Addition is: 60
Addition is: 80
Addition is: 110
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contain a sub-routines Main() and a user define function AddNum().

The Main() subroutine is the entry point for the program. Here, we called the three variants of the AddNum() function with a different number of arguments.

The AddNum() function accepts three arguments, here the 2nd and 3rd are optional parameters. The optional parameters contain a default value. If we will not pass the value for optional parameters then it will use the default value.

VB.Net User-defined Functions Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.