Call by Reference in C# Using the `ref` Keyword: Modifying Variables within Methods

Learn how to use C#'s `ref` keyword to implement call by reference, allowing methods to directly modify variables passed as arguments. This tutorial explains the mechanism of call by reference, demonstrates its use, and highlights its importance in scenarios where methods need to alter the original variables.



Call by Reference in C# Using the `ref` Keyword

Introduction

In C#, the `ref` keyword enables call by reference. Unlike call by value (where a copy of the variable's value is passed to a method), call by reference passes the memory address of the variable. Any changes made to the parameter within the method directly affect the original variable.

Using the `ref` Keyword

To pass an argument by reference, use the `ref` keyword both in the method signature and when calling the method.

Example: Demonstrating Call by Reference

Call by Reference Example

using System;

namespace CallByReference {
    class Program {
        public void Show(ref int val) {
            val *= val;
            Console.WriteLine($"Value inside Show(): {val}");
        }

        static void Main(string[] args) {
            int val = 50;
            Program program = new Program();
            Console.WriteLine($"Value before Show(): {val}");
            program.Show(ref val);
            Console.WriteLine($"Value after Show(): {val}");
        }
    }
}
Example Output

Value before Show(): 50
Value inside Show(): 2500
Value after Show(): 2500
        

Explanation

The `Show()` method modifies its parameter `val`. Because `val` is passed by reference, this modification directly affects the original variable in the `Main()` method. Notice that the value is changed *after* the method call.

Important Considerations

  • The variable must be initialized before being passed by reference.
  • Call by reference can modify the original variable, which can be both advantageous and potentially dangerous if not handled carefully.

Conclusion

Call by reference using `ref` provides a way to modify variables directly within methods. This is powerful but requires careful attention to avoid unintended consequences. Understand when this technique is needed and use it responsibly.