I have not read the original please visit: [Dry Goods to attack]c#7.0 new features (VS2017 available)
No more nonsense, go straight to the point.
First we know that the REF keyword is passing the value to a reference pass
So let's take a look at ref locals (ref local variable)
The code is as follows:
static void Main (string[] args)
{
int x = 3;
ref int x1 = ref x; Notice here that we assign x to x1 x1 = 2 by ref keyword
;
Console.WriteLine ($ "Variable {nameof (x)} value is: {x}");
Console.ReadLine ();
}
This code eventually outputs "2"
Note that we assign X to x1 through the REF keyword, and if the value type is passed, then the X will have no effect or output 3.
The benefit is self-evident, in some specific occasions, we can directly use ref to refer to the transfer, reducing the value of the need to open up the space.
Next we look at ref returns (ref reference return)
This function is actually very useful, we can return the value type as a reference type
The old rules, we'll raise a chestnut, the code is as follows:
Very simple logic. Gets the specified object value of 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 you just made
x =;
The value of Console.WriteLine ($ "Array arr[2] is: {arr[2]}");
Console.ReadLine ();
We return the reference type through ref, the value in the ARR array, and the corresponding change.
To sum up: The REF keyword exists very early, but he can only use it for parameters, this time c#7.0 lets him not only pass as a parameter, but also as a local variable and return value
Well, that's all.
Thank you for your kind attention.