How is the ‘ref’ keyword used in C#?
In C#, using the “ref” keyword allows parameters to be passed by reference instead of by value. With the “ref” keyword, a method can modify the value of the parameter passed to it, and these modifications will remain valid outside of the method.
Here is an example of how to use the ref keyword:
using System;
class Program
{
static void Main()
{
int number = 10;
Console.WriteLine("Before: " + number);
ChangeNumber(ref number);
Console.WriteLine("After: " + number);
}
static void ChangeNumber(ref int num)
{
num = 20;
}
}
In the example above, the ChangeNumber method uses the ref keyword to pass the num parameter by reference, allowing changes to the value of num parameter within the method to affect the number variable in the Main method.