C# Ref Returns

C# Ref Returns

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.

class Program    
{  
  static void Main(string[] args)   
  {    
    long total = 0;    
    AuthorByRefParam(5, 10, ref total);    
    Console.WriteLine(total);  
    Console.ReadKey();    
  }    
  static void AuthorByRefParam(long a, long b, ref long total)    
  {    
    total = a + b;    
  }    
}  

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, the 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 typeif you’re not familiar with these concepts.

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

class Program    
{    
static void Main(string[] args)    
{    
// Create an array of author names   
string[] authors = { "Mahesh Chand", "Mike Gold", "Dave McCarter", "Allen O'neill", "Raj Kumar" }  
// Call a method that returns by ref    
ref string author4 = ref new Program().FindAuthor(3, authors);    
Console.WriteLine("Original author:{0}", author4);    
// Prints 4th author in array = Allen O'neill    
Console.WriteLine();    
// Replace 4th author by new author. By Ref, it will update the array    
author4 = "Chris Sells";    
// Print 4th author in array  
  Console.WriteLine("Replaced author:{0}", authors[3]);    
//Prints Chris Sells    
Console.ReadKey();    
}    
public ref string FindAuthor(int number, string[] names)    
{    
if (names.Length > 0)    
return ref names[number]; // return the storage location, not the value    
throw new IndexOutOfRangeException($"{nameof(number)} not found.");    
}  

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/


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.