Next I will summarize my views on the out and ref parameters:
1. Similarities Between out and ref reference parameters: parameters are passed to the function through reference;
2. The difference between out and ref reference parameters is that the parameter is passed through ref reference. This parameter must be initialized and cannot be initialized in the function that calls it. The following example is incorrect:
Namespace refConsoleApp
{
Class MyRefClass
{
Static void MyRefMethod (ref int I)
{
Int I = 20;
}
Static void main (string [] args)
{
Int value; // not initialized the value;
MyRefMethod (ref value );
Console. WriteLine ("The value is {0}", value );
}
}
}
3. Use the out parameter to reference multiple parameters to return multiple values, which allows the method to return the required values at will. the following example:
Namespace multi_outConsoleApp
{
Class MyMultipleoutClass
{
Static void MyMultipleMethod (out int I, out string str1, out string str2)
{
I = 20;
Str1 = "I was born ";
Str2 = "zhaoqing ";
}
Static void Main (string [] args)
{
Int value;
String s1, s2;
MyMultipleMethod (out value, out s1, out s2 );
Console. WriteLine ("The integer value is {0} The first string value is {1} The second string value is {2}", value, s1, s2 );
}
}
}
The result is as follows:
The integer value is 20
The first string value is I was born
The second string value is zhaoqing
4. if one method uses ref to reference a parameter, and the other method uses out to reference the parameter, the functions with the same method name cannot be overloaded. Otherwise, a compilation error occurs. The following example shows: "cannot define overloaded methods that differ only on ref and out"
Namespace overloadofConsoleApp
{
Class overloadofclass
{
Static void MyMethod (ref int I)
{
I = 20;
}
Static void MyMethod (out int I)
{
I = 40;
}
Static void Main (string [] args)
{
Int refvalue = 0;
MyMethod (ref refvalue );
Console. WriteLine ("The value is {0}", refvalue );
&