This article mainly introduces the C # 7.0 of ref locals and returns, that is, local variables and references return, with a certain reference value, interested in small partners can refer to
Have not seen the original, please visit: [Dry Goods to attack]c#7.0 new features (VS2017 available)
Don't say much nonsense, go straight to the chase. First we know that the REF keyword is passing a value to a reference pass, so let's take a look at ref locals (ref local variable)
The following code is shown below:
static void Main (string[] args) { int x = 3; ref int x1 = ref x; Note here that we assign x to x1 x1 = 2 through the ref keyword ; Console.WriteLine ($ "changed variable {nameof (x)} value: {x}"); Console.ReadLine (); }
This code eventually outputs "2"
In the note section, we assign X to x1 with the REF keyword, and if the value type is passed, it will have no effect on X or Output 3.
The benefits are self-evident, in certain situations, we can use ref directly to refer to the transfer, reducing the value of the space needed to pass.
Next we look at ref returns (ref reference back)
This feature is actually very useful, and we can return the value type as a reference type.
The usual, we'll give a chestnut, the code is as follows:
Very simple logic. Gets the specified subscript value for the specified array
Static ref int Getbyindex (int[] arr, int ix) = ref Arr[ix]; Gets the specified subscript for the specified array
We write 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 =; The value of Console.WriteLine ($ "Array arr[2] is: {arr[2]}"); Console.ReadLine ();
We return the reference type through ref, and in the re-assignment, the values in the ARR array also change accordingly.
To summarize: The REF keyword has existed very early, but he can only use parameters, this time c#7.0 let him not only as a parameter, but also as a local variable and return value
All right, that's all.