C# Methods - Pass by Value
When the argument or parameter of a method is passed by value, then the method takes only the value of parameter and any changes made to the parameter inside the method have no effect on the parameter. By default, C# uses pass by value method which means that code within a method will not change the parameter used to pass in the method.
Example:
In the example below, the method called Square is created which returns square of the passed argument. The method modify the parameter as square of itself before returning it. In the main() method, when the passed argument is printed after calling the method Square, the value of the parameter remains unaffected because it was passed by value.
using System; class MyProgram { static int Square(int x) { x = x*x; return x; } static void Main(string[] args) { int x = 5; Console.WriteLine("Initial value of x: "+ x); Square(x); Console.WriteLine("Value of x, after passed by value: "+ x); } }
The output of the above code will be:
Initial value of x: 5 Value of x, after passed by value: 5
❮ C# - Methods