C# Program to Demonstrate Pass by Reference
Posted by Superadmin on August 15 2022 07:54:27

C# Program to Demonstrate Pass by Reference

 

 

This is a C# Program to demonstrate pass by reference parameter.

Problem Description

This C# Program Demonstrates Pass by Reference Parameter.

Problem Solution

Here Passing by reference enables function members, methods to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword.

Program/Source Code

Here is source code of the C# Program to Demonstrate Pass by Reference Parameter . The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Demonstrate Pass by Reference Parameter 
 */
using System;
class Program
{
    static void Main(string[] args)
    {
        int val;
        val = 4;
        Console.WriteLine("Value Before : {0}", val);
        square(ref val);
        Console.WriteLine("Value After : {0}", val);
        Console.Read();
    }
    static void square(ref int refParam)
    {
        refParam *= refParam;
    }
}
Program Explanation

This C# program is used to demonstrate pass by reference parameter. We have already defined the value for ‘val’ variable as 4. Then we are calling the square() function by passing ‘val’ variable value as an argument.

 

Here passing by reference enables function members, methods to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword.

Runtime Test Cases
 
Value Before : 4
Value After : 16