Home »
VB.Net »
VB.Net Programs
VB.Net program to demonstrate the pass by value mechanism in user define sub-routine
By Nidhi Last Updated : November 13, 2024
Pass by value in user defined sub-routine
Here, we will create a user define sub-routine that will accept two arguments as a pass by value. The modification in the pass by value arguments does not reflect in the calling function or sub-routine.
Program/Source Code:
The source code to demonstrate the pass by value mechanism in user define sub-routine is given below. The given program is compiled and executed successfully.
VB.Net code to demonstrate the example of pass by value in user defined sub-routine
'VB.Net program to demonstrate the pass by value mechanism
'in user define sub-routine.
Module Module1
Sub Swap(ByVal num1 As Integer, ByVal num2 As Integer)
Dim num3 As Integer = 0
num3 = num1
num1 = num2
num2 = num3
Console.WriteLine("Values inside the sub-routine:")
Console.WriteLine("Num1: {0}", num1)
Console.WriteLine("Num2: {0}", num2 & vbCrLf)
End Sub
Sub Main()
Dim num1 As Integer = 0
Dim num2 As Integer = 0
Console.WriteLine("Enter number1: ")
num1 = Integer.Parse(Console.ReadLine())
Console.WriteLine("Enter number2: ")
num2 = Integer.Parse(Console.ReadLine())
Swap(num1, num2)
Console.WriteLine("Values outside the sub-routine:")
Console.WriteLine("Num1: {0}", num1)
Console.WriteLine("Num2: {0}", num2)
End Sub
End Module
Output
Enter number1:
10
Enter number2:
20
Values inside the sub-routine:
Num1: 20
Num2: 10
Values outside the sub-routine:
Num1: 10
Num2: 20
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains two sub-routines Main() and Swap().
The Main() subroutine is the entry point for the program. Here we read two integer numbers from the user and pass them into the Swap() sub-routine.
The Swap() is the user-defined subroutine. Here, we pass two arguments using pass by value mechanism. To use pass by value mechanism we need to use the ByVal keyword. In this sub-routine, we exchange the values of arguments and print them on the console screen. But the modification in arguments does not reflect outside the sub-routine.
VB.Net User-defined Functions Programs »