SoFunction
Updated on 2025-03-07

Ref locals and returns in C# 7.0

If you haven't read the original text, please move:[Dry goods coming] New features of C# 7.0 (VS2017 is available)

Without further ado, just get to the point. First of all, we know that the ref keyword is to pass the value into a reference, so let's take a lookref locals(ref local variable)

The column subcode is as follows:

static void Main(string[] args)
  {

   int x = 3;
   ref int x1 = ref x; //Note here, we assign x to x1 through the ref keyword   x1 = 2;
   ($"Changes variables {nameof(x)} The value is: {x}");
   ();

  }

This code finally outputs "2"

Pay attention to the comment part. We assign x to x1 through the ref keyword. If it is a value type, it will have no effect on x, and it will still output 3.

The benefits are self-evident. In some specific occasions, we can directly use ref to reference and pass, reducing the space required for value pass.

Next, let's take a lookref returns (ref reference returns)

This function is actually very useful. We can use the value type as a reference type to return.

As the old rules, let’s give you a chestnut, the code is as follows:

Very simple logic...get the value of the specified subscript of the specified array

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

We write the test code as follows:

   int[] arr = { 1, 2, 3, 4, 5 };
   ref int x = ref GetByIndex(arr, 2); //Calling the method just now   x = 99;
   ($"Arrayarr[2]The value of: {arr[2]}");
   ();

We return the reference type through ref, and in reassign the value, the value in the arr array has also changed accordingly.

To sum up: the ref keyword existed very early, but it can only be used for parameters. This time, C# 7.0 allows it to be passed as a parameter, but also as a local variable and return value.

OK, that's all.

Thank you for your support.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.