OutAndRefParameters are often used to get values by passing parameters through methods. When your method does not have more than one return value, these two parameters play a role. Ref is the address for passing parameters, and out is the return value. There are some similarities between the two, but there are also differences. In this article, I will explain how to use these two parameters in the c # application.
1,OutParameters
OutThe method parameter keyword allows the method reference to pass to the same variable of the method. When the control is passed back to the call method, any changes made to the parameters in the method will be reflected in this variable.
Public class mathClass
{
Public static int TestOut (out int iVal1, out int iVal2)
{
IVal1 = 10;
IVal2 = 20;
Return 0;
}
Public static void Main ()
{
Int I, j; // variable need not be initialized
Console. WriteLine (TestOut (out I, out j ));
Console. WriteLine (I );
Console. WriteLine (j );
}
}
2,RefParameters
RefThe method parameter keyword allows the method reference to pass to the same variable of the method. When the control is passed back to the call method, any changes made to the parameters in the method will be reflected in this variable.
Static void Main (string [] args)
{
// Ref sample
Int refi; // variable need not be initialized
Refi = 3;
RefTest (ref refi );
Console. WriteLine (refi );
Console. ReadKey ();
}
Public static void RefTest (ref int iVal1)
{
IVal1 + = 2;
}
3. Differences
You must assign values to variables before using ref.
The out function will clear the variable, even if the variable has been assigned a value, it will not work. When exiting the function, all variables referenced by the out function will be assigned a value, and the ref reference can be modified or not modified.