Meaning of value types and reference types, stacks and heaps
This article mainly discusses the meaning of stacks and heaps, that is, the two types of C # categories : value types and reference types;
Although we are mostly reference types in the Framework class library in. NET, our programmers use most of the value types.
Reference types such as: String,object,class are always allocated from the managed heap, and the new operator in C # returns the memory address of the object-that is, the memory address that points to the object data.
The following is a table of value types and reference types:
Let's take a look at the following code:
first, declare in class a class , and a struct structure,
and invoke them at the program entrance, using:
Now let's take a look at how they are stored in memory.
As you can see from this graph, objects instantiated by Class(classes) point to the allocated space in the memory heap
Objects that are instantiated by struct (struct) are allocated in the memory stack
Next, let's make the following changes to the above program:
Red box, the code defines a class instantiation object S2, and assigns the object S1 to S2
Blue box, the code defines a struct instantiation object R2, and assigns the object R1 to R2
So what is the result of their output? Please select ()
A, the value of S1 is: The value of S2 is 222
The value of R1 is: The value of R2 is 666
B, the value of S1 is: The value of S2 is 222
The value of R1 is: The value of 666 R2 is 666
C, the value of S1 is: the value of 222 S2 is 222
The value of R1 is: The value of R2 is 666
D, the value of S1 is: the value of 222 S2 is 222
The value of R1 is: The value of 666 R2 is 666
Click to view answers
The correct answer is: C
Why is that? So let's take a look at how multiple value types and reference types are stored in memory,
, as you can see, the two reference type S1,S2 all point to the space on the same trailer heap,
When a change occurs, it changes in the same way.
The structure is a value type, although using R2=R1, the R1 object is assigned to R2,
But it allocates a separate space in the thread stack,
When you modify the value of an object, it does not affect the other object
Therefore, the difference between a value type and a reference type is:
1, they are stored in different locations
2, if it is a reference type, when two objects point to the same place, modify one of the time, the value of other objects will change
Case code Download
Meaning of value types and reference types, stacks and heaps