The out and ref parameters are often used to obtain values by passing parameters in a method. 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. out parameters
The out 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. ref Parameters
The ref 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 be initialized
Refi = 3;
RefTest (ref refi );
Console. WriteLine (refi );
Console. ReadKey ();
}
Public static void RefTest (ref int iVal1)
{
IVal1 + = 2;
}
Differences between ref and out parameters
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.
(3) params Parameters
The params keyword specifies that the parameter method parameter is used when the number of parameters is variable.
After the params keyword in the method declaration, no other parameters are allowed, and only one params keyword is allowed in the method declaration.
Using System;
Class App
{
Public static void UseParams (params object [] list)
{
For (int I = 0; I <list. Length; I ++)
{
Console. WriteLine (list [I]);
}
}
Static void Main ()
{
// The general practice is to first construct an object array and then use this array as a parameter of the method.
Object [] arr = new object [3] {100, 'A', "keywords "};
UseParams (arr );
// After using the params modifier parameter, we can directly use a group of objects as parameters
// Of course, this set of parameters must meet the parameter requirements of the called Method
UseParams (100, 'A', "keywords ");
Console. Read ();
}