Use of the. net keyword params

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.