CLR via C # learning notes (6) method Parameter Correlation (out ref Params)

Source: Internet
Author: User
Document directory
  • Out
  • Ref
  • Variable number of parameters
  • Method parameter type

The book CLR via C # has been roughly read twice before, but has never been able to understand it in depth, and a lot of content has been forgotten. Now I want to read it again, and write the read part, because the write process is also a process of deep understanding. This series is a learning record and can be easily accessed by myself later. If it is helpful to everyone, I am very happy. I read books selectively, so the order may be different from the order in the book.

Generally, when using a method, the parameters of the method are passed by value. If the parameter is a reference object, the address of the referenced object is passed to the method. If a value-type instance is passed, a copy of the instance is passed to the method. Parameters can be passed by reference in the method, and the out and ref keywords are used in C. The following describes the use of out and ref.

Out

1 When Using out, The out keyword is used for Parameter definition of the method and call of the method, as shown below:

Static void main (string [] ARGs) {string name = string. empty; getstr (out name); // Add out console when calling. writeline (name);} Private Static void getstr (out string name) // out {name = "oec2003" when the method parameter is defined ";}

 

2. If a method has an out-modified parameter, you must assign a value to the parameter before the method ends. Otherwise, the compilation fails. The Code is as follows:

Static void main (string [] ARGs) {string name = "oec2003"; getstr (out name); console. writeline (name);} Private Static void getstr (out string name) {// name is not assigned, during compilation, the "name" value must be assigned to the // out parameter before the current method is controlled to exit "exception occurs}

3. When calling a method with an out parameter, it is not necessary to assign an initial value to the out parameter because the value is not passed to the method, if you want to forcibly use the out parameter within the method, there will be a compilation error. The Code is as follows:

Static void main (string [] ARGs) {// assign the out parameter name the initial value oec2003 string name = "oec2003"; getstr (out name); console. writeline (name);} Private Static void getstr (out string name) {name = "hello" + name; // before the call, although the value is oec2003, // However, the following error occurs: "Out parameter name is not assigned "}

4. The out parameter is usually used when multiple values are returned in a method.

5. If the number and type of parameters of the two methods are the same, but the difference is that one of them is the out parameter, the two methods can be reloaded and the following code can run normally.

private static void GetStr(out string name) {    name = "oec2003";}private static void GetStr(string name){    name = "oec2003";}

 

Ref

1. Like the out parameter, when using ref, the ref keyword is used for Parameter definition and method call.

2. If the ref parameter does not have an initial value and cannot be compiled before calling the method, check the following code:

Static void main (string [] ARGs) {string name; getstr (ref name); // if the name is not assigned a value, the console cannot be compiled. writeline (name);} Private Static void getstr (ref string name) {name = "oec2003 ";}

3. Unlike out, the value of the ref parameter can be passed into the method for operations.

Static void main (string [] ARGs) {string name = "oec2003"; getstr (ref name); console. writeline (name); // return: Hello oec2003} Private Static void getstr (ref string name) {name = "hello" + name ;}

4 because ref has an initial value when passing in the method, you can perform any operation on the ref parameter within the method, so that the value of the ref parameter will not change.

Static void main (string [] ARGs) {string name = "oec2003"; getstr (ref name); console. writeline (name); // if no operation is performed in the method, oec2003} Private Static void getstr (ref string name) {} is still returned ){}

5. The same as the out parameter. If both methods have the same number and type, the only difference is that one of the parameters is the ref parameter, and the two can be overloaded.

For CLR, the keyword out and the keyword ref are equivalent, that is, both out and ref generate the same il code, because of this, if the difference between the two methods is only the difference between out and ref, the two methods cannot be overloaded. The following code:

// The following code compilation will report the error "Private Static void getstr (ref string name) {name =" oec2003 ";} private Static void getstr (out string name) {name = "oec2003 ";}
Variable number of parameters

Sometimes, if the number of parameters of a method can be changed based on the user's needs, it will bring great convenience. Methods such as Concat and format of the string type provide variable parameters. You can use Params to define variable parameters in C #, as shown in the following code:

Static void main (string [] ARGs) {console. writeline (add (1, 2, 3, 4);} public static int add (Params int [] num) {int sum = 0; foreach (int I in num) {sum + = I;} return sum ;}

It is very easy to use variable parameters. Note that the variable parameters must be of the array type. Although variable parameters are easy to use, the method of accepting variable parameters may cause some performance loss during the call, so that the array object must be allocated to the stack, and the Array Memory needs to be recycled by GC. To avoid this performance loss, we can define several methods without the Params keyword During writing, in this way, the method with the Params keyword is used only in special cases. Some class methods in C # Do the same, for example:

Method parameter type

When declaring the method parameter type, we should try to use only the weak type. For example, if you want to write a method to operate a group of data items, it is best to use an interface (such as ienumerable) to define the type of the method parameter, rather than using some strong data types such as list or some strong interface types (such as ilist or icollection), as follows:

// Use the weak type parameter private void operatecollection <t> (ienumerable <t> collection) {}// use the strong type parameter private void operatecollection <t> (list <t> collection ){}

The strong and weak types mentioned here can be understood as the type hierarchy. If the parent class has a higher level than the Child class, the higher the hierarchy, the weaker the type. The iemumerable interface is directly in the system. in the collections namespace, it is the base class of some other collection classes and interfaces (such as icollection ilist list). Therefore, the parameter is defined as ienumerable, all parameters that inherit the ienumerable type can be passed into the method, greatly improving the flexibility.

Series of related articles

CLR via C # learning notes (1) primitive type value type reference type

CLR via C # Study Notes (2) packing and unpacking

CLR via C # learning notes (3) constants and fields (cosnt readonly)

CLR via C # learning notes (4) method Constructor

CLR via C # learning notes (5) Performance of static Constructors

CLR via C # learning notes (6) method Parameter Correlation (out ref Params)

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.