The source code to demonstrate Pass by reference parameter passing is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to demonstrate Pass by Reference
//Parameter passing in a method.
using System;
class Sample
{
static void Swap(ref int X, ref int Y)
{
int Z = 0;
Z = X;
X = Y;
Y = Z;
}
static void Main()
{
int X = 10;
int Y = 20;
Console.WriteLine("Before swapping : X " + X + ", Y " + Y);
Swap(ref X, ref Y);
Console.WriteLine("After swapping : X " + X + ", Y " + Y);
Console.WriteLine();
}
}
Output:
Before swapping : X 10, Y 20
After swapping : X 20, Y 10
Press any key to continue . . .
Explanation:
In the above program, we created a Sample class that contains two static methods Swap() and Main() method.
The Swap() method will interchange the values of parameters with each other, and in the Main() method, we created two local variables X and Y. Then swap the values using the Swap() method and print the swapped value on the console screen.
Program:
The source code to demonstrate Pass by reference parameter passing is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Sample class that contains two static methods Swap() and Main() method.
The Swap() method will interchange the values of parameters with each other, and in the Main() method, we created two local variables X and Y. Then swap the values using the Swap() method and print the swapped value on the console screen.