C # parameters of series articles,

Source: Internet
Author: User

C # parameters of series articles,

Main problems solved:

Main content of the article:

  • Optional and named Parameters
  • Implicit local variables
  • PASS Parameters to methods by reference
  • Passing a variable number of parameters to a method
  • Design Specifications for parameters and return types
  • Constants

1.1 optional and named Parameters

Rules and principles for specifying default values for some parameters in the method:

  • You can specify the default value for methods, constructor methods, and parameters with parameter attributes (C # indexer. The default value must be a constant value that can be determined during compilation. It can be a primitive type. The Enumeration type is any reference type whose skill is set to null. You can use default and new to set the default value.
  • Do not rename the parameter variables (otherwise, the caller must modify the code when passing real parameters by passing parameter names ). If a method is called outside the module, do not change the default value. For example:
    // Do not do this private static string MakePath (string filename = "Untitled") {return string. format (@ "C :\{ 02.16.txt", filename);} // you need to perform this private static string MakePath (string filename = null) {return string. format (@ "C :\{ 02.16.txt", filename ?? "Untitled ");}

     

  • If the parameter is identified by the ref or out keyword, the default value cannot be set, because there is no way to pass meaningful default values for these parameters.

When calling a method, the rules and principles for passing parameters are as follows:

  • The named parameter can only appear at the end of the real parameter list.
  • All required real parameters must be passed
  • If the parameter requires ref/out, the following syntax is used to pass the real parameter by passing the parameter name:
// Method declaration private static void M (ref int x ){.......} // call the method int a = 5; M (x: ref );

In addition, the parameter types of methods cannot be declared using var. Do not confuse dynamic and var. Using var to declare local variables is just a simplified syntax. The Compiler requires that the compiler deduce the specific data type based on the expression. It can only declare local variables within the method, while the dynamic keyword applies to local variables, fields and parameters. In addition, the variables declared with var for initialization must be displayed.

 

1.2 pass the parameter (out ref) to the method by reference)

By default, all method parameters in CLR are passed values. For the reference type, the object pointer is passed to the method. This pointer is also passed as a value, meaning that the method can modify the object. For the value type, because it is on the stack and the transfer method is a copy, the instances in the caller are not affected.

CLR does not differentiate out and ref, and generates the same IL code no matter which one is used. In addition to a bit, the metadata is used to indicate whether it is an out or a ref, and the rest is almost the same. The out flag indicates that the caller does not expect that you have initialized the object before calling the method. The called method cannot read the parameter value. Therefore, the value must be written to the interface before returning the object. With the ref mark, the caller must first initialize the parameter value. Using out for a large value type can improve code execution efficiency, because it avoids copying fields of the Value Type instance during method calling.

CLR allows methods to be overloaded based on whether the out or ref parameters are used. For example:

// The following two methods can be used to implement overloading. // However, if there is only a difference between out and ref, it is invalid, // because the metadata form of the two signatures is the same as that of public class Point {void Add (Point p ){.....}; void Add (ref Point p ){.....};}

 

1.3 pass variable parameters to the Method

Use the following statement to accept variable parameters:

int Add(params int[] values){   int sum =0;   if(values!=null)   {      for(int x = 0; x<values.length;x++){.....}    }   return sum}

It can be Add (new int [] {1, 2, 3...}) or Add (1, 2, 3 ...);

When detecting a method call, the compiler checks all methods with the specified name and the parameter does not apply the ParamArray feature. Find and generate the Code required to call it. Otherwise, check the method that applies the ParamArray feature. At this time, the compiler generates code to construct an array, fill in elements, and then generate code to call the selected method.

Only the last parameter of the method can be marked with the Params keyword, and only a group of arrays (of any type) can be identified. null or no value can be passed;

A variable number of call parameters may affect the performance (unless null is explicitly passed ). After all, the array object must be allocated on the stack, the array elements must be initialized, And the Array Memory must eventually be garbage collected. To this end, you can define several overloaded versions that do not use the params keyword.

1.4 Design Specifications for parameters and return types

Specify the weakest type as far as possible for declaring method parameter types, and prefer interfaces rather than base classes. For example, if you want to process a set of data items, you 'd better use IEnumerable <T> instead of List <T> or ICollection <T> or IList <T>. The reason is to make the acceptable parameter range as wide as possible and more flexible. On the contrary, the return type of the method is declared as the strongest type (to avoid being limited to a specific type ). In short, make sure that the caller can call the method as flexible as possible to make the method more suitable.

Sometimes the internal implementation of the modification method is not affected by the caller. If the method returns List <string>, you may modify the internal method implementation to return string [] in the future. If you want to maintain a certain degree of flexibility, you can select a weak return type. For example, IList <string> does not recommend that you use the weakest IEnumerable <string> or use strong IConllction <string>

 

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.