What are ref locals and ref returns in C#?
Overview
In C#, a reference of a value can be returned, and such return values can also be stored inside a variable by the caller. The former characteristic is called ref return and the latter is called ref local.
Ref return
Ref return allows the function to return a reference value, rather than a copy of the value itself, to the caller.
Syntax
ref dataType functionName() {
return ref variableName;
}
Notice that the return type of the function is specified by dataType; however, it is prepended by the ref keyword. Moreover, in order to return a reference, we need to specify the ref keyword in the return statement as well.
Restrictions
- The scope of
variableNamemust be accessible tofunctionName. - The scope of
variableNamemust persist inside the caller offunctionName. - The
refkeyword cannot be used with a function that has the return typevoid.
Ref local
Ref local allows the declaration of a variable that can store a reference to another variable. Usually, ref local is used in conjunction with ref return, as it allows the reference value that is returned to be stored inside a local variable.
Syntax
ref dataType variableName = someReference
Here, variableName is a reference variable of type dataType that can store a reference inside. someReference can be a return value from a function call, or it can be any other variable. We need to prepend the value by the ref keyword like so: ref otherVariableName or ref functionName().
Example
class HelloWorld {static ref int getLastInt(int[] array) {return ref array[array.Length - 1];}static void Main() {int[] nums = {1, 2, 3, 4, 5};ref int lastNum = ref getLastInt(nums);System.Console.WriteLine("Last Number:");System.Console.WriteLine(lastNum);}}
Output is as follows:
Last Number:
5
In the example above, the getLastInt function takes an int array and returns a reference to the last element. We pass our nums array and store the returned reference value in the lastNum variable and then print it.
Free Resources