ref is a parameter modifiers in C# that allow you to pass arguments to methods by reference, rather than by value. This means that changes made to the parameter inside the method will affect the original variable outside the method.
The ref keyword is used to pass a parameter by reference. When you pass a variable to a method using ref, both the caller and the callee have access to the same memory location.
Example:
using System;
class Calculator
{
public void multiplyByFive(ref int num)
{
num = num * 5; // Modify the original value
Console.WriteLine("num value in Inside method = " + num);
}
}
class MyExample
{
static void Main()
{
int number = 5;
Calculator cal = new Calculator();
// Pass number by reference using 'ref'
cal.multiplyByFive(ref number);
Console.WriteLine("num value in Outside method = " + number);
}
}
Output:
num value in Inside method = 25
num value in Outside method = 25
num value in Outside method = 25
Explanation:
- The num parameter in the multiplyByFive method is passed by reference using the ref keyword.
- The method multiplyByFive the value of num, and this change is reflected in the number variable outside the method.