What are Ref locals and Ref returns in C# 7.0?

CsharpServer Side ProgrammingProgramming

A reference return value allows a method to return a reference to a variable, rather than a value.

The caller can then choose to treat the returned variable as if it were returned by value or by reference.

The caller can create a new variable that is itself a reference to the returned value, called a ref local.

In the below example even though we modify the color it doesn't have any mpact on the original array colors

Example

class Program{
   public static void Main(){
      var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
      string color = colors[3];
      color = "Magenta";
      System.Console.WriteLine(String.Join(" ", colors));
      Console.ReadLine();
   }
}

Output

blue green yellow orange pink

To acheive this we can make use of ref locals

Example

public static void Main(){
   var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
   ref string color = ref colors[3];
   color = "Magenta";
   System.Console.WriteLine(String.Join(" ", colors));
   Console.ReadLine();
}

Output

blue green yellow Magenta pink

Ref returns

In the below example even though we modify the color it doesn't have any mpact on the original array colors

Example

class Program{
   public static void Main(){
      var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
      string color = GetColor(colors, 3);
      color = "Magenta";
      System.Console.WriteLine(String.Join(" ", colors));
      Console.ReadLine();
   }
   public static string GetColor(string[] col, int index){
      return col[index];
   }
}

Output

blue green yellow orange pink

Example

class Program{
   public static void Main(){
      var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
      ref string color = ref GetColor(colors, 3);
      color = "Magenta";
      System.Console.WriteLine(String.Join(" ", colors));
      Console.ReadLine();
   }
   public static ref string GetColor(string[] col, int index){
      return ref col[index];
   }
}

Output

blue green yellow Magenta pink
raja
Published on 19-Aug-2020 14:05:08
Advertisements