Back to Asp.net series-basics (III)

Source: Internet
Author: User

 

Demo of small value type and reference type

 

When we use a reference type, we are actually processing the type pointer, not the type itself. When we use the value type, we are using the value type itself. Sounds confused, right?

The example is the best description.

Assume that we execute the following methods:

Public int ReturnValue ()
{
Int x = new int ();
X = 3;
Int y = new int ();
Y = x;
Y = 4;
Return x;
}

We will get the value 3, which is very simple, right?

Assume that we first use the MyInt class

Public class MyInt
{
Public int MyValue;
}

Then, execute the following method:

Public int ReturnValue2 ()
{
MyInt x = new MyInt ();
X. MyValue = 3;
MyInt y = new MyInt ();
Y = x;
Y. MyValue = 4;
Return x. MyValue;
}

What will we get ?... 4!

Why ?... How does x. MyValue become 4 ?... Let's look at what we have done and then we know what is going on:

In the first example, everything is as planned:

Public int ReturnValue ()
{
Int x = 3;
Int y = x;
Y = 4;
Return x;
}

In the second example, we do not get "3" because the variables "x" and "y" both point to the same object in the heap.
Public int ReturnValue2 ()
{
MyInt x;
X. MyValue = 3;
MyInt y;
Y = x;
Y. MyValue = 4;
Return x. MyValue;
}

We hope that the above content will give you a better understanding of the basic differences between the value type and the reference type in C #, and have a basic understanding of when pointers and pointers are used.

 

The author stays up late

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.