Introduction
In C#, the ref keyword is used to send and return references to and from Methods. Any change made to a value supplied by reference will be reflected because you are changing the deal at the address rather than the value itself. It can be used in the following scenarios:
- To reference an argument and pass it to a method.
- To create a method signature that returns a variable reference.
- To declare a struct as a ref struct.
- As a local example.
Recommended Topic - singleton design pattern in c#
Example: Passing Value Type Variable
using System;
public class Program
{
public static void Main()
{
int num = 10000;
// pass value type
Example(num);
Console.WriteLine(num);
Console.ReadLine();
}
public static void Example(int n)
{
n = 100;
}
}
Output
10000The value passes the value type variable num in the preceding Example. As a result, changes to the Example () method do not affect num, whereas the reference type variable myStr is sent by reference to the ProcessString() method. As a result, any modifications to the ProcessString() method will be reflected. Value type variables must occasionally be passed by reference. So, how do you go about it?
The keywords ref and out in C# allow us to transmit value type variables to another function using references.
The ref keyword is used to transmit a value type variable by reference in the following Example.




