In C#, the ref, out, and in keywords are used to pass arguments by reference to methods. This means that instead of passing a copy of the variable, a reference to the original variable is passed. However, these keywords serve different purposes and have distinct behaviors. Let's explore each one in detail.
Ref keyword
Ref keyword is used to pass the value as a reference type inside a function and if it's changed inside a function, the value outside the function will also change since both points to the same address.
using System;
public class Program
{
public void Demofunc(ref int a)
{
a = 10;
Console.WriteLine("Inside function "+a);
}
public static void Main(string[] args)
{
int a = 5;
Program p = new Program();
Console.WriteLine("Before calling the function "+a);
p.Demofunc(ref a);
Console.WriteLine("After calling the function "+a);
}
}
Output:
Before calling the function 5
Inside function 10
After calling the function 10
Out keyword
Out keyword is also very similar to ref keyword the only difference between both is,while passing it as an out keyword
initializing the value is not mandatory but in case of ref keyword it's mandatory.Out keyword is also used to return multiple values from function.
using System;
public class Program
{
public void Demofunc(out int a)
{
a = 10;
Console.WriteLine("Inside function "+a);
}
public static void Main(string[] args)
{
Program p = new Program();
p.Demofunc(out int a);
Console.WriteLine("After calling the function "+a);
}
}
Output:
Inside function 10
After calling the function 10
In keyword
In keyword is used to pass the value as a reference type but it's not possible to change the value inside the function,modifying the value within the function will cause a error with a message "Cannot assign to variable 'in int' because it is a readonly variable".
using System;
public class Program
{
public void Demofunc(in int a)
{
Console.WriteLine("Inside function "+a);
}
public static void Main(string[] args)
{
int a= 10;
Program p = new Program();
Console.WriteLine(" Before calling the function "+a);
p.Demofunc(in a);
Console.WriteLine("After calling the function "+a);
}
}
Output:
Before calling the function 10
Inside function 10
After calling the function 10
Top comments (2)
Nice start.
Usefull one 🫡