Ref Return and Ref Local in C# 7.0

Introduction 

 
C# 7.0 introduces ref returns and ref locals. The main goal of these new features is to make it easier for developers to pass around references to value types instead of copies of their values. This is important when working with large data structures that are implemented as value types.
C# allows passing parameters by reference, but a method was not able to return a reference. This has been changed with C# version 7.0.
 

Current ref and out approach

 
We can use ref and out arguments for sending some variables to the method and let it modify the value of this method. This way we can write methods that “return” more than one value. Ref lets the value type in by reference. Out means that the variable will get a value in the method where it is given as an argument.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         string fName = string.Empty; // must be initialized  
  4.         string lName; //optional  
  5.         GetFirstName(ref fName);  
  6.         Console.WriteLine($ "FirstName : {fName}");  
  7.         GetLastName(out lName);  
  8.         Console.WriteLine($ "Last Name : {lName}");  
  9.         Console.ReadLine();  
  10.     }  
  11.     static void GetFirstName(ref string fName) {  
  12.         fName = "Prasad";  
  13.     }  
  14.     static void GetLastName(out string lName) {  
  15.         lName = "Raveendran";  
  16.     }  
  17. }  
In the example above, you can see the differences between ref and out keywords in action. In the first few lines, we assign a value to fName but not lName, because fName will be passed through an argument using the ref keyword, meaning that an initial value must be assigned to it. The out keyword value (lName) isn’t defined until the called method towards the end of the code, because it must be defined in the called method before being passed to the calling method.
 

Ref Return

 
A method that returns a reference return value must satisfy the following two conditions:
  • The method signature includes the ref keyword in front of the return type.
  • Each return statement in the method body includes the ref keyword in front of the name of the returned instance.
  1. public class RefReturn {  
  2.     private int value = 10;  
  3.     public ref int Get() {  
  4.         return ref this.value;  
  5.     }  
  6.     public void Display() {  
  7.         Console.WriteLine($ "RefReturn : {this.value}");  
  8.     }  
  9. }  
In this example, the Get method in RefReturn returns the private field value by reference. If value were read-only, the compiler would not permit it to be returned by reference.
 

Ref Local

 
To store a reference into a local variable, define the local variable as a reference by adding the keyword ref before the variable type and add the keyword ref before the method call.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         REfLocalAndReturnTest();  
  4.         Console.ReadKey();  
  5.     }  
  6.     public static void REfLocalAndReturnTest() {  
  7.         var refReturn = new RefReturn();  
  8.         ref int _reflocal = ref refReturn.Get();  
  9.         int local = refReturn.Get();  
  10.         refReturn.Display();  
  11.         Console.WriteLine($ "RefLocal: {_reflocal}");  
  12.         Console.WriteLine($ "Local: {local}");  
  13.         _reflocal = 10;  
  14.         local = 20;  
  15.         change(_reflocal);  
  16.         refReturn.Display();  
  17.         Console.WriteLine($ "RefLocal: {_reflocal}");  
  18.         Console.WriteLine($ "Local: {local}");  
  19.     }  
  20.     public static void change(int value) {  
  21.         value = 30;  
  22.     }  
  23. }  
Output
 
REfReturn : 10
RefLocal: 10
Local: 10
REfReturn : 10
RefLocal: 10
Local: 20
 
From the output, we see that _reflocaldoes indeed reference the private variable refReturn.value, as its value has changed too. Whereas localcontains a copy, as changing its value has no effect on refReturn.value. Finally, the call to change shows that when ref locals are accessed without the refkeyword, they behave just like normal locals and are passed by value to other methods.
 

Other Uses

 
Referencing Array Elements
 
It is possible to return a reference to arrays.
 
Please find the example below, we are trying to modify the character array:
  1. public static void ReferrencingArrayElement() {  
  2.     char[] values = {  
  3.         'A',  
  4.         'E',  
  5.         'B',  
  6.         'O',  
  7.         'U'  
  8.     };  
  9.     Console.WriteLine($ "Before : {string.Join("", values)}");  
  10.     ref char value = ref ReplaceNonVowel(values);  
  11.     value = 'I';  
  12.     Console.WriteLine($ " After :{string.Join("", values)}");  
  13. }  
  14. public static ref char ReplaceNonVowel(char[] array) {  
  15.     return ref array[2];  
  16. }  
Output
 
Before : A,E,B,O,U
After :A,E,I,O,U
 
Referencing Local Variables
 
We can also reference other local variables:
  1. public static void ReferencingLocalVariable() {  
  2.     int age = 10;  
  3.     ref int changeAge = ref age;  
  4.     Console.WriteLine($ "Before: age= {age} and changeAge={changeAge}");  
  5.     changeAge = 20;  
  6.     Console.WriteLine($ "After: age= {age} and changeAge={changeAge}");  
  7. }  
Output
 
Before: age= 10 and changeAge=10
After: age= 20 and changeAge=20
 
In the upcoming tutorials, we will be discussing:
  • Local Functions
  • Pattern Matching
  • Improved Features,

    • Expression-Bodied Members,
    • throw Expressions,
    • Numeric Literals,
    • Out Parameters -> Out Variables
    • Out Wildcards