C# - Passing Parameters by Reference



A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

Declaring a Reference Parameter

You can declare the reference parameters using the ref keyword.

Syntax

Below is the syntax for declaring a reference parameter in C#:

void MethodName(ref DataType parameterName){
...
...
}

Calling a Method with a Reference Parameter

You can call a method with reference parameters using the ref keyword when passing arguments.

MethodName(ref variableName);

Example of Reference Parameter

The below example demonstrates the use of a method that swaps the values of two variables using reference parameters −

using System;
namespace CalculatorApplication {
   class NumberManipulator {
      public void swap(ref int x, ref int y) {
         int temp;
   
         temp = x; /* save the value of x */
         x = y;    /* put y into x */
         y = temp; /* put temp into y */
      }
      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();
         
         /* local variable definition */
         int a = 100;
         int b = 200;
   
         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);
   
         /* calling a function to swap the values */
         n.swap(ref a, ref b);
   
         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
   
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

It shows that the values have changed inside the swap function and this change reflects in the Main function.

When to Use Reference Parameters?

1. Modify Original Variable

Reference parameters allow a method to modify the original variable instead of working on a copy. This is useful when you need to update values inside a method.

Consider the following example where a bank updates a customer's balance:

using System;
namespace ReferenceParameterExample {
   class BankAccount {
      public void Deposit(ref double balance, double amount) {
         balance += amount; // Modifies the original balance
         Console.WriteLine("Balance after deposit: $" + balance);
      }

      static void Main(string[] args) {
         BankAccount account = new BankAccount();

         double balance = 500.00;
         Console.WriteLine("Initial Balance: $" + balance);

         // Calling the Deposit method
         account.Deposit(ref balance, 200.00);

         Console.WriteLine("Final Balance: $" + balance);

         Console.ReadLine();
      }
   }
}

The original balance is modified since it is passed by reference −

Initial Balance: $500.00
Balance after deposit: $700.00
Final Balance: $700.00

2. Passing Large Objects

You can pass large objects using reference parameters, which helps to improve performance as it avoids creating copies of large objects.

Consider the following example where a company updates employee details:

using System;

class Person {
    public string Name;
    public int Age;
}

class Program {
    public void UpdatePerson(ref Person p) {
        p.Name = "Updated Name";
        p.Age += 1;
        Console.WriteLine("Updated Details: " + p.Name + ", Age: " + p.Age);
    }

    static void Main() {
        Person p = new Person { Name = "Sudhir Sharma", Age = 28 };
        Console.WriteLine("Before Update: " + p.Name + ", Age: " + p.Age);

        Program program = new Program();
        program.UpdatePerson(ref p);

        Console.WriteLine("After Update: " + p.Name + ", Age: " + p.Age);
    }
}

The employee details are updated because the object is passed by reference −

Before Update: Sudhir Sharma, Age: 28  
Updated Details: Updated Name, Age: 29  
After Update: Updated Name, Age: 29
Advertisements