C# Program to Demonstrate Pass by Value

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

Problem Description

This C# Program Demonstrates Pass by Value Parameter.

Problem Solution

Here Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable.

Program/Source Code

Here is source code of the C# Program to Demonstrate Pass by Value 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 Value Parameter 
 */
using System;
class program
{
    static void Cube(int x)
    {
        x = x * x * x;
        Console.WriteLine("Value Within the Cube method : {0}", x);
    }
    static void Main()
    {
        int num = 5;
        Console.WriteLine("Value Before the Method is called : {0}", num);
        Cube(num);
        Console.WriteLine("Value After the Method is called : {0}", num);
        Console.ReadKey();
    }
}
Program Explanation

In this C# program, we are reading the two integer variables ‘num1’ and ‘num2’ respectively. In pass by value method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function.

advertisement
advertisement

In pass by value, the changes made to formal arguments in the called function have no effect on the values of actual arguments in the calling function. The swap() function is used to interchange the num1 and num2 variable values by using temporary variable temp.

Runtime Test Cases
 
Value Before the Method is called : 5
Value Within the Cube method : 125
Value After the Method is called : 5

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.