c#4.0 named parameters and optional parameters

Source: Internet
Author: User

Possible default parameters in C # 4.0

C # 4.0 now supports the use of default parameters for methods, constructors, and indexers (Note: VB supports default parameters for a few years).

When the default value of the parameter is specified as part of the declaration, the parameter is default. For example, the following method accepts 2 parameters, one "category" String parameter and another "PageIndex" integer parameter. The "PageIndex" parameter has a default value of 0, which is therefore a default parameter:

When calling the method above, we can explicitly pass 2 parameters to it:

Or we can omit to pass the second argument, in which case the default value of 0 is passed in:

Note that the IntelliSense for VS 2010, when the display statement is complete, indicates which parameter is default, and which of its defaults:


Mingshi parameter and default parameters in C # 4.0

C # 4.0 now also supports the concept of "Mingshi parameters". This allows you to explicitly name the arguments passed to a method, rather than identifying it by the location of the argument.

For example, I could write the following code to identify the second parameter passed to the getproductsbycategory method by its name (to make it a bit more explicit):


When a method supports multiple default parameters, and you want to specify which arguments to pass, it is useful to have Mingshi attendees. For example, below we have a dosomething method that accepts 2 default parameters:


We can make the appliance Mingshi and invoke the above method in any of the following ways:

Because 2 parameters are default, the default value of the parameter that is not specified is passed in when only 1 (or 0) parameters are specified.

c#4.0 named parameters and optional parameters

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.