C# Tutorial C# Advanced C# References

C# Methods - Pass by Reference



When the argument or parameter of a method is passed by reference, then the method takes the parameter as reference and any changes made to the parameter inside the method will change the parameter 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 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 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