C# 7 ref And out

‘ref’ & ‘out’ keywords are very popular & useful in C# and some more enhancement has been done for ref & out in C# 7. I am going to explain all the basic concepts & usage of ‘ref’ and ‘out’ keywords along with the following 3 topics which are part of C# 7.

  1. ref returns
  2. ref Locals
  3. Inline out variable declaration (Declaring out variable directly while passing it as parameter.)

If you are looking for any other C# 7 features apart from the preceding 3 new enhancements, then you can visit the following articles on C# 7 which will help you to understand C# 7 in more detail.

  1. Top 10 New Features of C# 7 With Visual Studio 2017



  2. Visual Studio 15 Preview First Look & C# 7
  3. How to Compile & Test C# 7 Features

All the three concepts ‘ref returns’, ‘ref Locals’ & ‘Inline out variable declaration’ can be consolidated in a small program as shown in the following screen shot.


But before discussing C# 7 features I am going to explain basic concepts of ref & out.

Some basics concepts about ref and out
  1. ref and out both are passed as reference.
  2. out: Only for output not for input. It means we cannot pass a variable value as input using out parameter.
  3. ref: For input and output both. It means a variable passed with ref keyword can be used for input and output purposes as well.
  4. ref variable must be initialization before passing it as parameter.
  5. Out variable do not require initialization even if out variable is initialized before passing it as parameter then that initialization value cannot be accessed inside the method for which it has been passed as out variable.
  6. It is not necessary to manipulate the ref variable i.e. if a method is accepting a parameter with ref keyword it is not necessary to manipulate the ref variable before leaving the control.
  7. The method which is accepting a parameter as out must assign the value of ‘out’ parameter before leaving the control. In C# 7
  1. There is no need to declare out variable before passing it as argument (inline out variable declaration).
  2. A method can return a variable as reference (ref return)
  3. we can use ‘ref’ keyword with local variables which is known as ref locals.

Now I am going to prove each statement by examples

ref and out both are passed as reference.

Code Snippet 

  1. static void Main(string[] args)  
  2.         {  
  3.             int x, y =0;  
  4.             DoSomething(out x, ref y);  
  5.             WriteLine($"x: {x} \ny: {y}");  
  6.         }  
  7.   
  8.         public static void DoSomething(out int x, ref int y)  
  9.         {  
  10.             x = 10;  
  11.             y = 20;  
  12.         }   

Output

x: 10

y: 20


As you can see in the preceding code snippet that whatever changes have been made to the variables x & y inside the method DoSomething() is also being reflected outside. Thus it proves that (ref & out) both are passed as reference.

out - Only for output not for input.

It means we cannot not pass a variable value as input using out parameter.



Code Snippet 1 

  1. static void Main(string[] args)  
  2. {  
  3.     int x = 20;  
  4.     DoSomething(out x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }  
  7. public static void DoSomething(out int x)  
  8. {  
  9.     //Use of unassigned out parameter 'x'  
  10.     x += 10;  
  11. }   

Compiler Error: “Use of unassigned out parameter 'x'”

If I change ‘out’ parameter to ‘ref’ parameter then see what will happen

Code Snippet 2 

  1. static void Main(string[] args)  
  2. {  
  3.     int x = 20;  
  4.     DoSomething(ref x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }  
  7. public static void DoSomething(ref int x)  
  8. {  
  9.     x += 10;  
  10. }   

Output

Value of x is :30

In the following code snippet, I am going to remove ‘ref’ keyword.

Code Snippet 3 

  1. static void Main(string[] args)  
  2. {  
  3.     int x = 20;  
  4.     DoSomething(x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }  
  7. public static void DoSomething(int x)  
  8. {  
  9.     x += 10;  
  10. }   

Output

Value of x is :20

Code Snippet 4 

  1. static void Main(string[] args)  
  2. {  
  3.     int x = 20;  
  4.     DoSomething(out x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }  
  7. public static void DoSomething(out int x)  
  8. {  
  9.     x = 10;  
  10. }   

Output

Value of x is :10

So “code snippet 1” & “code snippet 4” proves that ‘out’ is Only for output not for input.

ref: For input and output both.

A variable passed with ref keyword can be used for input and output purposes as well.


Code Snippet 
  1. static void Main(string[] args)  
  2. {  
  3.     int x =20;  
  4.     DoSomething(ref x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }         
  7. public static void DoSomething(ref int x)  
  8. {  
  9.     WriteLine($"Value of x is :{x}");  
  10.     x += 10;  
  11. }  

Output

Value of x is :20

Value of x is :30



ref variable must be initialization before passing it as parameter.

Code Snippet 1 

  1. static void Main(string[] args)  
  2. {  
  3.     int x;  
  4.     DoSomething(ref x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }  
  7. public static void DoSomething(ref int x)  
  8. {  
  9.       
  10. }   

Compiler Error: “Use of unassigned local variable 'x'”

Code Snippet 2 

  1. static void Main(string[] args)  
  2. {  
  3.     int x=55;  
  4.     DoSomething(ref x);  
  5.     WriteLine($"Value of x is :{x}");  
  6. }  
  7. public static void DoSomething(ref int x)  
  8. {  
  9.       
  10. }   

Build Status - Successful

So, the preceding 2 code snippet proves that ‘ref’ variable must be initialization before passing it as parameter.

Out variable do not require initialization

Out variable does not require initialization even if out variable is initialized before passing it as parameter then that initialization value cannot be accessed inside the method for which it has been passed as out variable.

It is not necessary to manipulate the ref variable.

If a method is accepting a parameter with ref keyword it is not necessary to manipulate the ref variable before leaving the control. 



The out parameter must be assigned to before control leaves the current method

The method which is accepting a parameter as out must assign the value of ‘out’ parameter before leaving the control. 

inline out variable declaration

There is no need to declare out variable before passing it as argument and it can be declared inline. This is a new feature in C# 7. Following is a screenshot for the same which explain the difference between C# 6 & C# 7 coding style for inline out variable.
If you look at the preceding screenshot closely then you will find that it is showing 3 dots just below the ‘int’ keyword. The 3 dots are saying something and if you open the quick action you will get the suggestion that “variable can be declared inlined”.


After fixing this the code snippet

  1. int result;  
  2. Add(10, 20, out result);     

Will be changed to

  1. Add(10, 20, out int result);   

So, in Visual studio 2017 support for inline variable declaration has been added and it also provides intellisence for inline variable declaration with information id “IDE0018”.

This inline variable will work with all the methods of C# which is accepting out parameter. Even though in-built methods of C# e.g. “DateTime.TryParse” will allow inline variable declaration. Following screenshot compare the code snippet of C# 6 & C# 7.

ref return

A method can return a variable as reference (ref return)

In C# 7 we can use ‘ref’ for return a variable from a method i.e. a method can return variable with reference.

Sample Code 

  1. int[] x = { 2, 4,62,54,33,55, 66,71,92};   
  2.   
  3. public ref int GetFirstOddNumber(int[] numbers)  
  4. {  
  5.     for (int i = 0; i < numbers.Length; i++)  
  6.     {  
  7.         if (numbers[i]%2==1)  
  8.         {  
  9.            return ref numbers[i];  
  10.         }  
  11.     }  
  12.     throw new Exception("odd number not found");  
  13. }   

But there are some restrictions and everything cannot be returned as reference like below code will give error, 

  1. Dictionary<int, decimal> ProductPriceList = new Dictionary<int, decimal>();  
  2. public ref decimal GetProductPriceReference(int productId)  
  3. {  
  4.     return ref ProductPriceList[productId];  
  5. }   

Error

CS8156 An expression cannot be used in this context because it may not be returned by reference

You may be thinking what is the need of ‘ref return’. It can be achieved with ref return also. Let me explain it with some more examples:

ref locals

we can use ‘ref’ keyword with local variables which are known as ref locals.

As you have seen in the previous example, I am searching for an odd number inside an integer array and if it is not found then it's throwing an exception. The method is not returning it as value but as reference. So, you need to store that value also which has been returned as reference. To store it in a local variable we can use ‘ref’ keyword with local variables which is known as ref locals.

Code snippet 

  1. int[] x = { 2, 4, 62, 54, 33, 55, 66, 71, 92 };  
  2. ref int oddNum = ref GetFirstOddNumber(x);   

Complete Code 

  1. using static System.Console;  
  2. namespace RefReturnsAndRefLocals  
  3. {  
  4.     class Program  
  5.     {  
  6.         public ref int GetFirstOddNumber(int[] numbers)  
  7.         {  
  8.             for (int i = 0; i < numbers.Length; i++)  
  9.             {  
  10.                 if (numbers[i] % 2 == 1)  
  11.                 {  
  12.                     return ref numbers[i]; //returning as reference  
  13.                 }  
  14.             }  
  15.             throw new Exception("odd number not found");  
  16.         }  
  17.         static void Main(string[] args)  
  18.         {  
  19.             Program p = new Program();  
  20.             int[] x = { 2, 4, 62, 54, 33, 55, 66, 71, 92 };  
  21.             ref int oddNum = ref p.GetFirstOddNumber(x); //storing as reference  
  22.             WriteLine($"\t\t\t\t{oddNum}");  
  23.             oddNum = 35;  
  24.             for (int i = 0; i < x.Length; i++)  
  25.             {  
  26.                 Write($"{x[i]}\t");                  
  27.             }  
  28.             ReadKey();  
  29.         }  
  30.     }  
  31. }   

output

In the above screenshot, you can see that first time the variable “OddNum” is storing the value 33 with its reference inside the array ‘x’. 

If you print “oddNum” first time, then it will print 33 but after that I have re-assigned its value and set “oddNum =35” now iterating the array and printing elements of array and you can see that whatever I have done modification for “oddNum” from outside is also reflecting inside the array and internal value has been modified from 33 to 35.

Method with ref return can be used as left hand side statement

If a method is using ref return in that case, we can put it left hand side in a statement whereas method without ref return cannot be used as left hand side of statement.

Complete Code for method without ref return 

  1. using static MethodWithoutRefReturn.DummyEmployees;  
  2. namespace MethodWithoutRefReturn  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             GetEmployee() = new Employee { Id = 2, Name = "Banketeshvar", Age = 28 };  
  9.         }  
  10.     }  
  11.   
  12.     class Employee  
  13.     {  
  14.         public int Id { get; set; }  
  15.         public string Name { get; set; }  
  16.         public int Age { get; set; }  
  17.     }  
  18.   
  19.     class DummyEmployees  
  20.     {  
  21.         public static Employee employee = null;  
  22.         public static Employee GetEmployee()  
  23.         {  
  24.             if (employee == null)  
  25.             {  
  26.                 employee = new Employee { Id = 1, Name = "Manish Sharma", Age = 27 };  
  27.             }  
  28.             return employee;  
  29.         }  
  30.     }  
  31. }  

Complete Code for method with ref return 

  1. using static MethodWithRefReturn.DummyEmployees;  
  2. namespace MethodWithRefReturn  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             GetEmployee() = new Employee { Id = 2, Name = "Banketeshvar", Age = 28 };  
  9.         }  
  10.     }  
  11.   
  12.     class Employee  
  13.     {  
  14.         public int Id { get; set; }  
  15.         public string Name { get; set; }  
  16.         public int Age { get; set; }  
  17.     }  
  18.   
  19.     class DummyEmployees  
  20.     {  
  21.         public static Employee employee = null;  
  22.         public static ref Employee GetEmployee()  
  23.         {  
  24.             if (employee == null)  
  25.             {  
  26.                 employee = new Employee { Id = 1, Name = "Manish Sharma", Age = 27 };  
  27.             }  
  28.             return ref employee;  
  29.         }  
  30.     }  
  31. }   

Apart from the above explained point about ref and out you can find more about ref & out in the following article,

Author
Banketeshvar Narayan
0 15.8k 5.7m
Next » C# 7 Digit Separator