Complete parsing of parameter passing in C #

Source: Internet
Author: User
I. Introduction

For some beginners (including those who have been working for several years), the problem of parameter passing between methods is sometimes confusing, because the basic questions for parameter passing are also frequently encountered during the interview process, such interview questions mainly check whether the developer base is solid, do you have a deep understanding of the C # median type and reference type? This is not a simple definition description of them, but a distribution in memory. Therefore, this article will give you an in-depth analysis of the parameter passing problems in C # and share my own understanding, you can analyze the results of passing parameters without running the program.

Ii. Pass by value

For parameter passing in C #, there are four types of parameters:

  • Value Type parameter passing by value
  • Pass reference type parameters by value
  • Pass value type parameters by reference
  • Transmit parameters of reference type by reference

However, by default, parameters in CLR methods are passed by value. To help you fully understand the transmission of parameters, we will analyze these four situations one by one.

2.1 value type parameter passing by value

For parameters, they are divided into the form parameters and real parameters. The form parameters refer to the parameters in the called method and the real parameters refer to the parameters of the called method. The following code helps you understand the concept of the form parameters and real parameters:

Class program {static void main (string [] ARGs) {int addnum = 1; // addnum is the real parameter, add (addnum);} // addnum is the form parameter, that is, the Private Static void add (INT addnum) {addnum = addnum + 1; console. writeline (addnum );}}

For value-based transmission, a copy of the value-type instance is passed, that is, the form parameter receives a copy of the real parameter, the called method operation is a copy of the real parameter, so it does not affect the parameter values in the original call method. To prove this, you can see the following code and running results:

Class program {static void main (string [] ARGs) {// 1. value Type by value transmission status console. writeline ("pass by value"); int addnum = 1; add (addnum); console. writeline (addnum); console. read ();} // 1. value Type: Private Static void add (INT addnum) {addnum = addnum + 1; console. writeline (addnum );}

The running result is:

It can be seen from the results that the value of addnum has not changed after the method is called. The call of the add method only changes the value of the addnum copy, so the value of addnum is changed to 2. However, our analysis is not over yet. In order to give you a deep understanding of transfer, we need to know why the value-based transfer of a value type parameter does not modify the value of a real parameter, I believe the following figure can explain all your doubts:

 

2.2 pass reference type parameters by value

When the passed parameter is of the reference type, the transfer and operation point to the reference of the object (see here, some friends will think that the reference is not passed at this time? Why is it passed by value? For this doubt, it is indeed passed by value. At this time, the address of the passed object is also the value of this address, so it is still passed by value ), in this case, the operation of the method changes the original object. For this reason, it may be difficult to understand the text description. The following code and analysis diagram are used to help you understand:

Class program {static void main (string [] ARGs) {// 2. refclass = new refclass (); addref (refclass); console. writeline (refclass. addnum);} // 2. private Static void addref (refclass addnumref) {addnumref. addnum + = 1; console. writeline (addnumref. addnum) ;}} class refclass {public int addnum = 1 ;}

The running result is:

Why does passing a reference modify the value of the original real parameter? For this, we will explain the parameter distribution in the memory:

2.3. Special Cases of passing values of the string reference type

The string type is also a reference type. However, when values of the string type are passed by value, the value of the reference type does not change the value of the real parameter. Many friends may be confused about this, let's take a look at the following code:

Class program {static void main (string [] ARGs) {// 3. special cases for passing string reference types by value string STR = "Old string"; changestr (STR); console. writeline (STR);} // 3. special cases of passing value of string reference type Private Static void changestr (string oldstr) {oldstr = "New String"; console. writeline (oldstr );}}

The running result is:

Why is the original value not changed?Because the string is "immutable", when the oldstr = "New String" code is executed in the called method, in this case, the value of "Old string" in oldstr is not directly modified to "New String", because the string type remains unchanged and cannot be modified. In this case, a memory is allocated again, then, change the value in the memory to "New String" and assign the address in the memory to the oldstr variable. At this time, STR still points to the "Old string" character, however, oldstr changes the direction, and it finally points to the "New String" string.. So the running result will be like the above. The following memory distribution chart can help you better understand the text expression:

3. Pass by reference

Whether it is a value type or a reference type, we can use the ref or out keyword to transmit parameters by reference. However, when transferring parameters by reference, pay attention to the following two points:

Both method definition and method call must use both ref and out explicitly; otherwise, a compilation error may occur.

CLR allows method overloading through out or ref parameters. For example:

# Region CLR allows out or ref parameters to overload the Private Static void add (string Str) {console. writeline (STR);} // The Compiler considers the following method as another method to overload the Private Static void add (ref string Str) {console. writeline (STR) ;}# endregion

Transferring by reference can solve the problem that the reference copy is changed when the value is passed without affecting the reference itself. In this case, the reference (that is, the address of the address) is passed ), instead of reference copies ). The Code passed by reference is as follows:

Class program {static void main (string [] ARGs) {# region transfers console by reference. writeline ("pass by reference"); int num = 1; string refstr = "Old string"; changebyvalue (ref num); console. writeline (Num); changebyref (ref refstr); console. writeline (refstr); # endregion console. read () ;}# region is passed by reference // 1. private Static void changebyvalue (ref int numvalue) {numvalue = 10; console. writeline (numvalue);} // 2. private Static void changebyref (ref string numref) {numref = "New String"; console. writeline (numref);} # endregion}

The running result is:

From the running results, we can see that the value of the reference itself has also been changed. The following figure helps you understand the method of transferring by reference:

Iv. Summary

Here, all the parameters are passed. In short,For pass by value, both the value type and the pass by value type are a copy of the real parameter, but only when the value type, in this case, a copy of the real parameter instance is passed (that is, a copy of the Value Type value), and a copy of the referenced real parameter is passed when the reference type is used. For pass by reference, the parameter address is passed, that is, the instance pointer.

 

Download all source code: Passing Parameters

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.