ref locals and returns for C 7.0 (local variable and reference return)

  • 2021-12-11 08:35:12
  • OfStack

If you haven't read the original text, please move: [Dry Goods Attack] C # 7.0 New Features (VS 2017 Available)

Don't talk too much nonsense, just get down to business. First of all, we know that the ref keyword is to change value passing into reference passing, so let's look at ref locals (ref local variable)

The column subcode is as follows:


static void Main(string[] args)
  {

   int x = 3;
   ref int x1 = ref x; // Pay attention here , We pass ref Keyword   Put x Assign to x1
   x1 = 2;
   Console.WriteLine($" Changed variable  {nameof(x)}  Value is : {x}");
   Console.ReadLine();

  }

This code finally outputs "2"

Note the comments. We assign x to x1 via the ref keyword. If it is a value type pass, it will have no effect on x, or output 3.

The benefits are self-evident. In some specific occasions, we can directly use ref to refer to passing, which reduces the space needed for value passing.

Next let's look at ref returns (ref reference returns)

This function is actually very useful, we can treat the value type as a reference type for return.

As usual, let's take a chestnut with the following code:

Simple logic.. Gets the specified subscript value of the specified array


static ref int GetByIndex(int[] arr, int ix) => ref arr[ix]; // Gets the specified subscript of the specified array 

We wrote the test code as follows:


   int[] arr = { 1, 2, 3, 4, 5 };
   ref int x = ref GetByIndex(arr, 2); // Call the method just now 
   x = 99;
   Console.WriteLine($" Array arr[2] The value of is : {arr[2]}");
   Console.ReadLine();

We return the reference type through ref, and in the re-assignment, the value in the arr array is changed accordingly.

To sum up 1: The ref keyword has existed for a long time, but it can only be used as parameters. This time, C # 7.0 allows it to be passed not only as parameters, but also as local variables and return values

Okay, that's all.

Thank you for your support.


Related articles: