The ref keyword in C# is used for passing or returning references of values to or from Methods. Basically, it means that any change made to a value that is passed by reference will reflect this change since you are modifying the value at the address and not just the value. It can be implemented in the following cases:
- To pass an argument to a method by its reference.
- To define a method signature to return a reference of the variable.
- To declare a struct as a ref struct
- As local reference
Example 1: Here, we define two methods addValue and subtractValue. The method addValue is a method that only modifies the value of its parameter. Therefore when the value of ‘a’ is displayed after passing it as a parameter to addValue there is no difference in its value. Whereas the method subtractValue uses the reference of the parameter, the keyword ref indicating the same. Hence when the value of ‘b’ is displayed after passing it as a parameter to subtractValue, you can see the changes are reflected in its value. The ref keyword must be used in the method definition as well as when the method is called.
C#
using System;
namespace ref_keyword {
class GFG {
static void Main( string [] args)
{
int a = 10, b = 12;
Console.WriteLine( "Initial value of a is {0}" , a);
Console.WriteLine( "Initial value of b is {0}" , b);
Console.WriteLine();
addValue(a);
Console.WriteLine( "Value of a after addition" +
" operation is {0}" , a);
subtractValue( ref b);
Console.WriteLine( "Value of b after " +
"subtraction operation is {0}" , b);
}
public static void addValue( int a)
{
a += 10;
}
public static void subtractValue( ref int b)
{
b -= 5;
}
}
}
|
OutputInitial value of a is 10
Initial value of b is 12
Value of a after addition operation is 10
Value of b after subtraction operation is 7
Example 2: You may use the keyword ref with an instance of a class as well. In the program given below, we have a class Complex to represent Complex numbers. The class also consists of an update method that uses the object’s reference and reflects the updates made in the value of the real and imaginary part of the object.
C#
using System;
namespace class_ref {
class Complex {
private int real, img;
public Complex( int r, int i)
{
real = r;
img = i;
}
public int getRealValue()
{
return real;
}
public int getImgValue()
{
return img;
}
public static void Update( ref Complex obj)
{
obj.real += 5;
obj.img += 5;
}
}
class GFG {
static void Main( string [] args)
{
Complex C = new Complex(2, 4);
Console.WriteLine( "Complex number C = " + C.getRealValue() +
" + i " + C.getImgValue());
Complex.Update( ref C);
Console.WriteLine( "After updating C" );
Console.WriteLine( "Complex number C = " + C.getRealValue() +
" + i " + C.getImgValue());
}
}
}
|
Output: Complex number C = 2 + i 4
After updating C
Complex number C = 7 + i 9