C# Call by Reference

Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter. To pass the parameters in C#, we have a keyword called ref.

It passes a reference to a memory location rather the actual value, so the changes made to this passed parameters are reflected o the main program that is their value can be modified permanently.


Example: C# call by reference

using System;

namespace Programs
{
   class Swapping
   {
      //swapping function (user-defined)
      public void swapFunc(ref int x, ref int y)
      {
         int temp;

         temp = x;
         x = y;
         y = temp;
      }

      //main method
      static void Main(string[] args)
      {
         Swapping swapObj = new Swapping();

         int a = 10, b = 20;

         Console.WriteLine("Before swapping, a: {0}", a);
         Console.WriteLine("Before swapping, b: {0}", b);

         //calling swap funciton with ref keyword
         swapObj.swapFunc(ref a, ref b);

         Console.WriteLine("\nAfter swapping, a: {0}", a);
         Console.WriteLine("After swapping, b: {0}", b);

      }
   }
}

Output:

Before swapping, a: 10
Before swapping, b: 20

After swapping, a: 20
After swapping, b: 10

Unlike call by value (from the previous tutorial), the swapped value of a and b can be seen in the output above.