Home > Article > Backend Development > What are Ref local variables and Ref return values in C# 7.0?
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
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(); } }
blue green yellow orange pink
To achieve this we can use ref locals
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(); }
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
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]; } }
blue green yellow orange pink
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]; } }
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!