C #4.0 optional parameters

Source: Internet
Author: User

One of the new features in C #4.0 is named parameters and optional parameters.

Naming parameters: when calling a method, you can specify the parameter name instead of passing parameters by location;

Private void func (string STR, int number, bool flag ){}

For the above functions, the name parameter can be fun (FLAG: True, Number: 10, STR: "zhangsan ");

Optional parameters: When declaring a parameter in a method, you can set the default value for it. When calling this method, this optional parameter can be ignored. The following principles must be followed:

1. The optional parameter must have a compile time as its default value. If it is a reference type other than string (including the SpecialDynamic type). The default value can only be null.

Private void func (string STR, int A = 10, people P = new people () is not compiled;

2. The optional parameter must appear after the non-optional parameter. The parameter on the right of the optional parameter (if any) must be an optional parameter.

Private void func (string STR, int A = 10, bool flag) This statement is not compiled;

Use private void func (string name, int age = 10, bool sex = false) {// do something;} as an example to describe how to call the named parameters and optional parameters: 

This. func ("zhangsan"); // ignore all optional parameters
This. func (sex: True, age: 30, name: "zhangsan"); // use the name parameter to change the order;
This. func ("zhangsan", 20); // use the preceding optional parameters in sequence without the optional parameter name;
This. func ("zhangsan", 30, true); // use all optional parameters without the optional parameter name;
This. func ("zhangsan", sex: false); // if you use the following optional parameter, you must use the optional parameter name; this. func ("zhangsan", false); cannot be compiled;
This. func ("zhangsan", age: 40 );

The preceding call methods are correct;

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.