Ref Returns In C# 7.0

The ref keyword in C# allows code to pass a value type variable by reference as a parameter of a method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.

  1. class Program    
  2. {  
  3.   
  4.   static void Main(string[] args)   
  5.   {    
  6.     long total = 0;    
  7.     AuthorByRefParam(5, 10, ref total);    
  8.     Console.WriteLine(total);  
  9.     Console.ReadKey();    
  10.   }  
  11.   
  12.   static void AuthorByRefParam(long a, long b, ref long total)    
  13.   {    
  14.     total = a + b;    
  15.   }  
  16.   
  17. }  

Listing 1

The code snippet in Listing 1, AuthorByRefParam, accepts the third parameter by reference. The caller program calls the method by initializing a variable and passes it as a parameter by explicitly using the ref keyword.

In C# 7.0, value can be returned and stored locally by ref.

C# 7.0 introduced an improved ref keyword that can be used to return values by ref. Ref can also be used for storing values by ref in the local variable. You may want to read the article, Concepts of C#: Value type vs Reference type, if you’re not familiar with these concepts.

The code snippet in Listing 2 lists a method, FindAuthor, that returns a string value by reference.

  1. class Program    
  2. {  
  3.   
  4. static void Main(string[] args)    
  5. {  
  6.   
  7. // Create an array of author names   
  8. string[] authors = { "Mahesh Chand""Mike Gold""Dave McCarter""Allen O'neill""Raj Kumar" };    
  9.   
  10. // Call a method that returns by ref    
  11. ref string author4 = ref new Program().FindAuthor(3, authors);    
  12. Console.WriteLine("Original author:{0}", author4);  
  13.   
  14. // Prints 4th author in array = Allen O'neill    
  15. Console.WriteLine();  
  16.   
  17. // Replace 4th author by new author. By Ref, it will update the array    
  18. author4 = "Chris Sells";  
  19.   
  20. // Print 4th author in array  
  21.   Console.WriteLine("Replaced author:{0}", authors[3]);  
  22.   
  23. //Prints Chris Sells    
  24. Console.ReadKey();  
  25.   
  26. }  
  27.   
  28. public ref string FindAuthor(int number, string[] names)    
  29. {  
  30.   
  31. if (names.Length > 0)    
  32. return ref names[number]; // return the storage location, not the value    
  33. throw new IndexOutOfRangeException($"{nameof(number)} not found.");  
  34.   
  35. }  

Listing 2

Summary

Ref returns is a new concept introduced in C# 7.0. In this article, we learned how to use this feature.

Next C# 7.0 Feature >> Local Functions In C# 7.0 

References

References used to write this article:

https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

Up Next
    Ebook Download
    View all
    Learn
    View all