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.

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.