Facebook Page Twitter Page LinkedIn Page
× C# Q&A


When the argument(s) or parameter(s) of a method is passed by reference, then the method takes the parameter(s) as reference and any changes made to the parameter(s) inside the method will change the parameter(s) itself also. By default, C# uses pass by value method. To pass an argument by reference ampersand ref keyword while defining and calling the method. To pass by reference means that the code within a method will change the parameter(s) used to pass in the method.

Example:

In the below example, 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 changes because it was passed by reference.

using System;
 
class MyProgram {
  static int Square(ref int x) {
    x = x*x;
    return x;
  }  

  static void Main(string[] args) {
    int x = 5;
    Console.WriteLine("Initial value of x: "+ x);
    Square(ref x);
    Console.WriteLine("Value of x after, passed by reference: "+ x);
  }
}

The output of the above code will be:

Initial value of x: 5
Value of x, after passed by reference: 25

❮ C# - Methods