18. ref Keyword in c#
C# supports built in data type value type and reference type. 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#.
Important point
- The ref keyword indicates that an argument is passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method
- You can declare the reference parameters using the ref keyword.
- A reference parameter is a reference to a memory location of a variable.
class Program
{
static void Main(string[] args)
{
int a = 4;
Console.WriteLine("Value before method call is: " + a);
GetData(a);
Console.WriteLine("Value after method call is: " + a);
Console.ReadLine();
}
public static void GetData(int a)
{
a = a + 990;
Console.WriteLine("Value inside method is: " + a);
}
}
Output:
Value before method call is: 4
Value inside method is: 994
Value after method call is: 4
When we use ref key inside the method call.We have a method named GetData which takes an ref parameter inside the method.
class Program
{
static void Main(string[] args)
{
int a = 4;
Console.WriteLine("Value before method call is: " + a);
GetData(ref a);
Console.WriteLine("Value after method call is: " + a);
Console.ReadLine();
}
public static void GetData(ref int a)
{
a = a + 900;
Console.WriteLine("Value inside method is: " + a);
}
}
see the difference between this output:-
Value before method call is: 4
Value inside method is: 904
Value after method call is: 904
hope you understand 'ref' keyword.