C# - Pass by Reference Parameter Passing in a Method

Here, we are going to learn how to implement pass by reference parameter passing in a method using C# program?
Submitted by Nidhi, on September 11, 2020 [Last updated : March 22, 2023]

Here, we demonstrate pass by reference parameter passing using the ref keyword. If we pass the parameter with the help of the ref keyword then changes made within the method will also reflect outside the method.

C# program for pass by reference parameter passing in a method

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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