The ref keyword indicates a value that is passed by reference. It is used in four different contexts:

  • In a method signature and in a method call, to pass an argument to a method by reference.
  • In a method signature, to return a value to the caller by reference.
  • In a member body, to indicate that a reference return value is stored locally as a reference that the caller intends to modify or, in general, a local variable accesses another value by reference.
  • In a struct declaration to declare a ref struct or a readonly ref struct.

Passing an argument by reference

When used in a method’s parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable.

1
2
3
4
5
6
7
8
9
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
}

int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 45

Reference return values

1
2
3
4
5
6
7
8
public static ref int Find(int[,] matrix, Func<int, bool> predicate)
{
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
if (predicate(matrix[i, j]))
return ref matrix[i, j];
throw new InvalidOperationException("Not found");
}

Ref locals

A ref local variable is used to refer to values returned using return ref.