VB.Net program to demonstrate the pass by reference mechanism in user define sub-routine

Here, we are going to demonstrate the pass by reference mechanism in user define sub-routine in VB.Net.
Submitted by Nidhi, on December 13, 2020 [Last updated : March 07, 2023]

Pass by reference in user defined sub-routine

Here, we will create a user define sub-routine that will accept two arguments as a pass by reference. The modification in the pass by reference arguments will also reflect in the calling function or sub-routine.

Program/Source Code:

The source code to demonstrate the pass by reference 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 reference in user defined sub-routine

'VB.Net program to demonstrate the pass by reference mechanism 
'in user define sub-routine.

Module Module1
    Sub Swap(ByRef num1 As Integer, ByRef 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: 20
Num2: 10
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 reference mechanism. To use the pass by reference mechanism we need to use the ByRef keyword. In this sub-routine, we exchange the values of arguments and print them on the console screen. The modification in arguments also reflects outside the sub-routine.

VB.Net User-defined Functions Programs »





Comments and Discussions!

Load comments ↻





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