C #4.0 named parameters and optional parameters,

Source: Internet
Author: User

C #4.0 named parameters and optional parameters,

Default parameters in C #4.0

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

When the default value of a parameter is specified as a part of the Declaration, the parameter can be defaulted. For example, the following method accepts two parameters: One "category" string parameter and the other "pageIndex" integer parameter. The "pageIndex" parameter has a default value of 0, so it is a default parameter:

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

Or we can omit passing the second parameter. In this case, the default value 0 will be passed in:

 

Note: When the display statement is complete, the intelliisense of VS 2010 indicates which parameter is default and its default value:


Named real parameters and default parameters in C #4.0

C #4.0 currently supports the concept of "named real parameters. This allows you to explicitly name the parameter passed to a method, rather than recognizing it by the real parameter location.

For example, you can write the following code and pass it through its name.GetProductsByCategoryThe second parameter of the method (to make its usage clearer ):


When a method supports multiple default parameters and you want to specify which arguments are passed, the named arguments are very useful. For example, we haveDoSomethingMethod, which accepts two default parameters:


We can use the named real parameter to call the above method in any of the following ways:

Because both parameters are default, when only one (or zero) parameter is specified, the default value of the unspecified parameter will be passed in.

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.