C# Program to Demonstrate Pass by Reference Parameter

«
»

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.

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

advertisement

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

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn