C # variable number of parameters in the Method

Source: Internet
Author: User

Declare a variable number of parameters: CopyCodeThe Code is as follows: static int add (Params int [] values)
{
Int sum = 0;
If (value! = NULL)
{
For (INT x = 0; x <values. length; X ++)
Sum + = values [x];
}
Return sum;
}

Except Params, this method is a common method that accepts the int array and returns the sum of all items in the group.

We can call: add (New int [] {1, 2, 3 });

However, reading is not very high, and we hope to be more concise:

Add (1, 2, 3 );

In this case, the Params keyword can be compiled and run.

Params can only be applied to the last of the method parameters.

When the C # compiler finds add (, 3), it first looks for the matching method of add (int I, Int J, int K,
If yes, call it. If no, check whether there is a method defined as add (Params int [] values,

If yes, save 1, 2, and 3 to an array, and then call the add (INT [] values) method.
It also shows that CLR does not know anything about the Params keyword. Params is only provided to the C # compiler.

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.