Out ---- transfer a reference
1. If a variable in a method uses out as a parameter, changes made to the out parameter in the method will reflect this variable.
Static VoidMethod (Out IntIvalue)
{
Ivalue = 44;
}
Static VoidMain ()
{
IntA;// Initialization is not requiredMethod (OutA );// Display the out keywordConsole. writeline ();// A is now 44}
2. To use the out parameter, the out keyword must be displayed for the method definition and call;
3. You do not need to initialize the variable passed as the out parameter. Because the out parameter clears itself after entering the method, you must assign a value to the out parameter before returning the method. (Only parameters with no value in the address cannot be accepted by. net ). Ref requires that the variables be initialized before being passed.
Ref ----- only an address!
1. When a method uses the ref parameter, any changes made to the ref parameter in the method will be reflected in the variable.
Static VoidMethod (Ref IntIvalue)
{
Ivalue = 44;
}
Static VoidMain ()
{
IntA = 0;// Initialization requiredMethod (RefA );// Display the ref keywordConsole. writeline ();// A is now 44}
2. If you use the ref parameter, you must pass the parameter as the ref parameter to the method. The ref parameter value can be passed to the ref parameter.
3. the variables passed by the ref parameter must be initialized, because the ref parameter is still its own after entering the method, and the address still points to the original value, for this reason, the ref parameter can not be operated internally in the method in which it is used. Unlike out, out parameters do not need to be initialized before being passed.
Out and ref examples
Public Static String Testout ( Out String Str)
{
STR =" Out Value ";
Return " Hello World ";
} Public Static Void Testref ( Ref String Str)
{
STR =" Ref Value ";
}
Public Static Void Testnoref ( String Refstr)
{
Refstr =" No ref ";
}
Static Void Main ()
{
String Outstr;
Console. writeline (testout (Out Outstr )); // Return value output "Return Value" Console. writeline (outstr ); // Output "out value" for the out parameter after the call" String Refstr; // Initialization required Testref ( Ref Refstr );
Console. writeline (refstr ); // Output "Ref value" for the ref parameter after the call" Testnoref (refstr ); // Do not use ref Console. writeline (refstr ); // Still output "Ref value"; not changed }