Home  >  Article  >  Backend Development  >  What are Ref local variables and Ref return values ​​in C# 7.0?

What are Ref local variables and Ref return values ​​in C# 7.0?

PHPz
PHPzforward
2023-09-11 22:37:02779browse

C# 7.0 中的 Ref 局部变量和 Ref 返回值是什么?

Reference return values ​​allow methods to return a reference to a variable instead of than a value.

The caller can choose to treat the returned variable as value or reference.

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

In the example below, even if we modify the color it has no effect Raw 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 achieve this we can use 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 example below, even if we modify the color, it will not have any impact Original array color

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

The above is the detailed content of What are Ref local variables and Ref return values ​​in C# 7.0?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete