C #4.0 new feature learning (1)-optional parameters, named parameters, and parameter Arrays

Source: Internet
Author: User

I learned new features of C #4.0: optional parameters, named parameters, and parameter arrays.

1. Optional parameters: Specify the default value for a specific method parameter. You can omit these parameters when calling a method.

Note:

(1) The optional parameter cannot be the 1st parameter in the parameter list. It must be placed after all required parameters (unless there are no required parameters );

(2) A default value must be specified for an optional parameter. The default value must be a constant expression and cannot be a variable;

(3) All optional parameters later must be optional.

2. Named parameters are called by named parameters. The real Parameter order can be different from that of the form parameter.

3. Parameter array. The parameter array is defined by the keyword Params. Different real parameters can be input during the call, providing great flexibility.

4. Specific Code:

// Optional parameter
Static int add (int A, int B = 2)
{
Return A + B;
}
// Parameter array, with the keyword Params
Static int add (Params int [] P)
{
Int sum = 0;
Foreach (int I in P)
Sum + = I;
Return sum;
}

Static void main (string [] ARGs)
{
Console. writeline (add (1 ));
Console. writeline (add (1, 3 ));
// Called using named parameters. The real Parameter order can be different from that of the form parameter.
Console. writeline (add (B: 6, A: 1 ));
// Call the method that uses the parameter Array
Console. writeline (add (1, 3, 5 ));
Console. writeline (add (1, 3, 5, 7 ));
Console. readkey ();
}

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.