You can specify a variable number of parameters for the params keyword.
You can send a comma-separated list of parameters of the specified type in the parameter declaration or a parameter array of the specified type. You can also choose not to send parameters.
After the params keyword in the method declaration, no other parameters are allowed, and only one params keyword is allowed in the method declaration.
The following example shows how to send parameters to params.
View plaincopy to clipboardprint? Public class MyClass
{
Public static void UseParams (params int [] list)
{
For (int I = 0; I <list. Length; I ++)
{
Console. Write (list [I] + "");
}
Console. WriteLine ();
}
Public static void UseParams2 (params object [] list)
{
For (int I = 0; I <list. Length; I ++)
{
Console. Write (list [I] + "");
}
Console. WriteLine ();
}
Static void Main ()
{
// You can pass multiple parameters separated by commas (,) to the method.
UseParams (1, 2, 3, 4 );
UseParams2 (1, 'A', "test ");
// No problem even if no parameter is passed
// The following code outputs only one blank line
UseParams2 ();
// You can also pass an array to the Method
// Of course, You need to match your type
Int [] myIntArray = {5, 6, 7, 8, 9 };
UseParams (myIntArray );
Object [] myObjArray = {2, 'B', "test", "again "};
UseParams2 (myObjArray );
// The following code will produce a compilation Error
// The reason is that the array cannot be converted to an int type array.
// UseParams (myObjArray );
// The following method does not return an error
// However, the entire int type array is treated as a parameter.
UseParams2 (myIntArray );
}
}
/*
Output result:
1 2 3 4
1 a test
5 6 7 8 9
2 B test again
System. Int32 []
*/
Author: "robot Learning logs"