C# supports value type and reference type data types. By default, the value type variable is passed by value, and the reference type variable is passed by reference from one method to another method in C#.
using System;
public class Program
{
public static void Main(string[] args)
{
int myNum = 10;
// pass value type
ProcessNumber(myNum);
Console.WriteLine(myNum);
Console.ReadLine();
}
public static void ProcessNumber(int num)
{
num = 100;
}
}
In the above example, the value type variable myNum is passed by value. So, changes in the ProcessNumber() method does not get reflected to myNum, whereas the reference type variable myStr is passed by reference to the ProcessString() method. So, any changes in the ProcessString() method will be reflected.
We sometimes need to pass the value type variables by reference. So, how to do it?
C# includes ref and out are keywords, which help us to pass the value type variables to another function by the reference.
The following example demonstrates passing a value type variable by reference using the ref keyword.
class Program
{
static void Main(string[] args)
{
int myNum = 10;
ProcessNumber(ref myNum); //use ref to pass the parameter by reference
Console.WriteLine(myNum);
Console.ReadLine();
}
public static void ProcessNumber(ref int num)
{
num = 100;
}
}
As you can see in the above example, the ProcessNumber() method specifies an int parameter with the ref keyword, so we must use the ref keyword while passing this parameter while calling ProcessNumber() method. A variable must be assigned a value before passing as an argument with the ref keyword.
We must specify the ref keyword when passing to the method. Otherwise, it will give a compile-time error.
static void Main(string[] args)
{
int myNum = 10;
ProcessNumber(myNum); //Compile-time Error: Must use ref keyword
Console.WriteLine(myNum);
Console.ReadLine();
}
public static void ProcessNumber(ref int num)
{
num = num + 100;
}
The method can include other parameters with the ref parameter, as shown below.
static void Main(string[] args)
{
int myNum = 10, val=0;
ProcessNumber(ref myNum, val);
Console.WriteLine(myNum);
Console.ReadLine();
}
public static void ProcessNumber(ref int num, int val )
{
num = num + val;
}
Ref and Out Parameter in Method Overloading
Both ref and out are treated the same as compile-time but different at runtime. We cannot define an overloaded method that differs only on 'ref' and 'out' parameter. The following will give a compiler error.
interface INumberProcessor
{
void ProcessNumber(ref int k, int j);
void ProcessNumber(out int k, int j);
}
However, we can define method overloading either ref or out parameters, as shown below.
interface INumberProcessor
{
void ProcessNumber(int k, int j);
void ProcessNumber(ref int k, int j);
void ProcessNumber(int k, ref int j);
}