The role of the Out, ref keyword:
In a function that uses out and ref as the key to the formal parameter, the function is called only if the parameter is modified in the body of the function.
The corresponding parameters are also changed, because the parameters that are decorated with the out ref are reference types, not value types, which means that they store the address instead of the value type. The value type becomes a reference type.
Out, ref keywords differ:
Out keyword: 1.out indicates extra return value.
2.out modified variable, method must be assigned inside a value
3.out modified parameters, passed in variables, can be unassigned, because a value must be assigned in the method
4. Usage scenarios: When multiple return values are required for a method, if the same type can be used as an array, if it is a different type of case, it needs to be out
Ref Keyword: 1. Ref modifier parameter, method inside can do nothing, can not go to assign value
2.ref parameters, must be assigned before the value is passed, and the opposite of out
Summary: Out is used only to pass values out of the method, regardless of the value passed in, out will be re-assigned value,
Ref decoration, requires an initial value, can be assigned or not assigned to a value in a method
Note : When calling out,ref decorated parameters, when passing in the actual parameters, the front is also added out or ref
Example: Swapping two numbers
1 Static voidMain (string[] args)2 {3 4 intNUM1 =Ten; To assign a value first5 intnum2 = -;6Console.WriteLine ("NUM1 = {0},num2 = {1}", num1,num2);7Change (refNUM1,refnum2);8Console.WriteLine ("NUM1 = {0},num2 = {1}", NUM1, num2);9 Console.readkey ();Ten } One A - Static voidChange (ref intAref intb) - { the inttemp =A; -A =b; -b =temp; -}
Out Example:
1 Static voidMain (string[] args)2 {3 intNUM1;4Test ( outNUM1);//out modifier, NUM1 can not be assigned value5Console.WriteLine ("NUM1 = {0}", NUM1);6 }7 8 9 Ten Public Static voidTest ( out inta) One { AA =Ten; -}
C # Basics _ keyword out, ref (12)