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

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 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.