Reference Type and ref transfer instance Final Solution

Source: Internet
Author: User

The difference between passing a ref variable before a reference type and passing a reference type variable without a ref variable is not clear all the time. Recently, a friend on the Internet gave me a question, after careful consideration and coding and testing, I finally understood the difference. The following is an example for you and your friends to understand and remember.

Ref is used to pass variables by reference, and the reference type itself also transmits variables by reference, so the difference between the two remains entangled? The differences between the two are as follows:

When no ref is added before the reference type, you can only modify the value of the referenced object, but not the reference of the referenced object.

When you add ref before the reference type, you can not only modify the value of the referenced object, but also change the reference of the referenced object.

The following test code can be well reflected. The Unsafe code (pointer) is used in the Code. By using the pointer to display the memory address of the object, you can observe the changes to the object reference.

Pass without ref:

 1 class Value
2 {
3 public int I = 15;
4}
5 class Program
6 {
7 static unsafe void Main (string [] args)
8 {
9 Program t = new Program ();
10 t. first ();
11}
12 public unsafe void first ()
13 {
14 int I = 5;
15 Value v = new Value ();
16 v. I = 25;
17
18 // view the IP address of the V instance
19 fixed (int * pi = & (v. I ))
20 {
21 Console. WriteLine ("V. I Address 0x {0: X}", (int) pi );
22}
23
24 second (v, I );
25
26 // address of the V instance after the second function is executed
27 fixed (int * pi = & (v. I ))
28 {
29 Console. WriteLine ("V. I Address 0x {0: X}", (int) pi );
30}
31
32 Console. WriteLine (v. I );
33}
34 public unsafe void second (Value v, int I)
35 {
36 I = 0;
37
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.