A point of caution when using C # parameters and arguments, reference types, and value types.

Source: Internet
Author: User

This is an example of discussion in the morning group.

1 Static voidMainstring[] Arg) {2 3 varp1=NewPerson{name="Zhang San"};4 varP2=NewPerson{name="John Doe"};
int i=0;5 A1 (p1,i);6 A2 (P2,ref i);7Console.WriteLine (P1. name+ "----" +i);//output Zhang San-----08Console.WriteLine (P2. name+ "----" +i);//Output Sun Six-----1
9

}
Ten

One voidA1 (stringPpp,int i) {
i++;  ppp=new person{name=" Harry "};  - }void A2 (string  ppp,ref int i) {
i++; PPP. Name=" magoroku "; +}

80% of old programmers in the output P1. The name was all wrong and thought it was Harry. I didn't understand it at first. The PPP of the reference type in A1 has changed, why is the output still "Zhang San"? Later the search data understood the key factor-"formal parameters and arguments are two different variables!" 】

The parameter is the argument at the time of the method declaration. PPP such as void A1 (string ppp). An argument is a parameter that is passed when a method is called. such as the P1 of A1 (p1).

Baidu knows a summary of a Daniel:
"The data transfer that occurs in a function call is one-way. That is, the value of the argument can only be passed to the parameter, and the value of the parameter cannot be passed to the argument in reverse. Therefore, during a function call, the value of the formal parameter changes, and the value in the argument does not change. 】
Because the A1 method, Ppp=new person{name= "Harry"}, the operation of the parameter PPP address changed, not the reference address of P1. This results in no effect on the P1 of the arguments.
Compare A2. The reference address for PPP and P2 is always the same. So the P1 has always had an impact.

A point of caution when using C # parameters and arguments, reference types, and value types.

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.