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.
- class Program {
- static void Main(string[] args) {
- string fName = string.Empty; // must be initialized
- string lName; //optional
- GetFirstName(ref fName);
- Console.WriteLine($ "FirstName : {fName}");
- GetLastName(out lName);
- Console.WriteLine($ "Last Name : {lName}");
- Console.ReadLine();
- }
- static void GetFirstName(ref string fName) {
- fName = "Prasad";
- }
- static void GetLastName(out string lName) {
- lName = "Raveendran";
- }
- }
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:
- public class RefReturn {
- private int value = 10;
- public ref int Get() {
- return ref this.value;
- }
- public void Display() {
- Console.WriteLine($ "RefReturn : {this.value}");
- }
- }
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.

Join the conversation! Your thoughts help the community grow.