Re-debugging: parameter transfer-transfer reference type

Source: Internet
Author: User

C # When the value type and reference type are passed as method parameters, they can both be called "value", but the "value" here refers to something different.

When a method parameter is of the value type, the method passes the value itself.

When the parameter of a method is of the reference type, the method passes the address of the application type reference, that is, the value of the reference type address on the stack.

Example of passing a reference type as a parameter

Code
   static void Main()
{
ArgsRef abf = new ArgsRef();
AddRef(abf);
Console.WriteLine(abf.i);
Console.Read();
}

private static void AddRef(ArgsRef abf)
{
//abf = new ArgsRef();
abf.i = 20;
Console.WriteLine(abf.i);
}


class ArgsRef
{
public int i = 10;
}

 

Assume that in the main method, argsref abf = new argref (); the stack address of abf is 0x10; then, addref (abf) is used in the process of passing the method ); it is actually a transfer address pointing, and this address pointing is also a copy of the original address.
Strictly speaking, it is also a "value" transfer, similar to abf = 0x10;
When the annotation in the demo is removed: In the addref method, if you execute abf = new argsref () Again, the abf address is changed, the new address is assigned to abf, which is assumed to be 0x11. In the method body
Abf is actually the object pointed to by 0x11. In the main method, the abf address in console. writeline (abf. I) is still 0x10,
Because the method is used to copy the passed address when passing the reference parameter, a copy of the passed value is consistent when passing the value type.
Therefore:
In the above example, if the first line of the method addref is commented out, the output result in the main method is: 20, 20; if the comment is removed, the output result is: 20, 10.

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.