The ref Parameter in C#
In this article, I will explain how do you use Ref parameter in C# applications.
Introduction
The ref keyword is used as a call by reference in C#. It is used to pass arguments by reference, if you make any changes to the passed parameter in the method the changes are reflected in the original variable which was passed as an argument. It is used both places; when we declare a method and when we call the method. The following example will explain how we use the ref parameter in C#. In this example we create a function (square) and pass a ref parameter in it, now we look at the value before we call the function and after we call the function.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class RefExample
{
public void square(ref int x)
{
x = x * x;
}
}
class Program
{
static void Main(string[] args)
{
RefExample tr = new RefExample();
int a = 5;
Console.WriteLine("The value of a before the function call: " + a);
tr.square(ref a);
Console.WriteLine("The value of a after the function call: " + a);
Console.ReadLine();
}
}
The output of following program