C # Optional parameters, named arguments, parameter arrays

Source: Internet
Author: User

Learn the new features of c#4.0: Optional parameters, named parameters, parameter arrays.

1, optional parameter, refers to the method's specific parameters to specify the default value, you can omit these parameters when calling the method.

But be aware that:

(1) The optional parameter cannot be the 1th parameter of the parameter list, and must be located after all required parameters (unless there is no required parameter);

(2) An optional parameter must specify a default value, and the default value must be a constant expression and cannot be a variable;

(3) All parameters after the optional parameter must be an optional parameter.

2, named parameters, refers to the call through named parameters, the actual parameter sequence can be different from the formal parameters.

3. Parameter array, define the parameter array through the keyword params. You can pass in a number of different arguments at the time of invocation, with good flexibility.

4, the specific code:

       //Optional parameters
        static int Add ( int a, int b = 2)
        {
             return a + B;
       }
       //parameter array, 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 by named arguments, the argument order can be different from the formal parameter
Console.WriteLine (Add (B:6, a:1));
Calling a method that uses a parameter array
Console.WriteLine (ADD (1, 3,5));
Console.WriteLine (ADD (1, 3, 5,7));
Console.readkey ();
}

C # Optional parameters, named arguments, parameter arrays

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.