Call By Reference
Call By Reference
On passing variables in a function, any changes made in the passed parameter will update the original variable’s reference too. To pass an argument as reference-type instead of the copy of the original value, i.e, to pass a reference of arguments to the function the ref keyword is used in C#.
Features of call by reference
- Changes in one object variable affect the other object variable.
- Actual and copied variables are created in the same memory location.
using System;
namespace MyApplication
{
class Test
{
public void Display(ref int x)
{
x += x;
Console.WriteLine("Value inside the function: "+ x);
}
static void Main(string[] args)
{
int x = 200;
Test abc = new Test();
Console.WriteLine("Value before calling: "+ x);
abc.Display(ref x);
Console.WriteLine("Value after calling: " + x);
}
}
}
OUTPUT
Value before calling: 200
Value inside the function: 400
Value after calling: 400