The meaning and use of ref and out in the original C #
When passing an argument to a method, the corresponding shape delegate is initialized with a copy of the argument , regardless of whether the formal parameter is a value type (for example, int), a nullable type (int?), or a reference type , which is true. That is, whatever changes are made inside the method without affecting the value of the argument. For example, for a reference type, a change to a method simply alters the referenced data, but the argument itself does not change, and it still references the same object.
The code is as follows:
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Namespace Ref_out { class program { static void Main (string[] args) { int i = 8; Console.WriteLine (i); Doincrease (i); Console.WriteLine (i); } static void Doincrease (int a) { a++; } } }
The results of the operation are as follows:
If you use the REF keyword, any actions applied to the parameter apply to the argument as well, because the parameters and arguments refer to the same object.
PS: Both the argument and the parameter must be prefixed with the REF keyword appended.
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Namespace Ref_out { class program { static void Main (string[] args) { int i = 8; Console.WriteLine (i); 8 doincrease (ref i); Ref Console.WriteLine (i) must also be added before the argument. The 9//ref keyword causes the action on the parameter to be applied to the argument } static void Doincrease (ref int a) //parameter must be ref { a++; } } }
The operation results are as follows
The ref argument must also be initialized before it is used , or it cannot be compiled.
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Namespace Ref_out { class program { static void Main (string[] args) { int i; The ref argument is not initialized, so the program cannot compile Console.WriteLine (i); Doincrease (ref i); Console.WriteLine (i); } static void Doincrease (ref int a) { a++; } } }
Sometimes we want the parameters to be initialized by the method itself , when the out parameter can be used.
The code is as follows:
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Namespace Ref_out { class program { static void Main (string[] args) { int i; No initialization //console.writeline (i);//Here I uninitialized, compile error doincrease (out i); The method is used to assign the initial value to the argument Console.WriteLine (i); } static void Doincrease (out int a) { a = 8; Initialize the a++ in the method ; A = 9 } }
The meaning of ref and out in C # and how to use it