C # method Note 1: C #4.0 new features: named parameters and optional parameters

Source: Internet
Author: User
Before C #4.0, to call a method, you must strictly follow the number, type, or even parameter sequence and method. But this problem can be solved in C #4.0.   1. optional parameter. It can be understood as two situations: ① if a parameter is not specified, a default value is given. ② If the parameter value is specified, the default value is not used. In this way, you do not need to judge every time or write a heavy-load function. CodeAs follows:
 Class  Program {  Static   Void Main ( String  [] ARGs) {program Program =New  Program ();  Int M = program. Add ( 10 ); //  Here M = 11; default B = 1;              Int N = program. Add ( 10 , 20 ); //  Here n = 30; Where B = 20;  }  Public   Int Add ( Int A, Int B = 1  ){  Return A + B; //  If the value of B is not specified when a function is called, the default value is 1;  }} 

 

    2. Name Parameters Optional parameters solve the default value of parameters, while named parameters solve the order of parameters. We generally determine the order of parameters when a method is called according to the parameter sequence when the method is defined, for example:    

  Class  Program {  Static   Void Main ( String  [] ARGs) {program Program = New  Program ();  Int M = 5  ;  Int N = 30 ;  Int Result = program. getlastnum (Y: n, x: m ); //  Note. The interchange between the positions of X and Y.  //  Not in the order required by the Method  }  Public   Int Getlastnum ( Int X, Int  Y ){  If (X <Y ){  Return  X ;}  Return   0  ;} 

 

                 
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.