C# program to demonstrate the example of Pass by reference parameter passing in a method

Here, we are going to learn about the pass by reference parameter passing in a method and its C# implementation.
Submitted by Nidhi, on September 11, 2020

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.

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.

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






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.