C # method variable number of parameters _c# tutorial

Source: Internet
Author: User
Declare a variable number of parameters:
Copy Code code 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;
}

The above method, which removes params, is a common method that takes an int array and returns the sum of the items in the group.

We can call this: Add (new int[]{1,2,3});

But reading is not very high, we want to be more concise:

ADD (1,2,3);

At this point, because the params keyword, can be compiled through and run.

Params can only be applied to the last one in a method parameter.

When the C # compiler discovers Add (1,2,3), it first looks for a way to match the add (int i,int j,int k).
If there is a call, no, find out if there is a method defined as add (params int[] values),

If so, save 1, 2, and 3 to an array, and then call the Add (int[] values) method.
It also shows that the CLR is ignorant of the params keyword, and params is only available to the C # compiler.
Related Article

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.