Value Before the Method is called : 5 Value Within the Cube method : 125 Value After the Method is called : 5
This is a C# Program to demonstrate pass by value parameter.
This C# Program Demonstrates Pass by Value Parameter.
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.
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(); } }
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.
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.
Value Before the Method is called : 5 Value Within the Cube method : 125 Value After the Method is called : 5