Differences between value types and reference types
1. Value Type and reference type
We divide the data types we learned into two sets:
Value Type
All numeric types (longint short byte ulong uint ushort sbyte decimal double float), bool, char, enumeration, and structure
Reference Type
String, array, Class
Division basis: their memory storage structure is different
2
, Value type and reference type Similarities and Differences
A. Similarities:
Whether it is a value type variable or a reference type variable, the variable is always open up in the stack space.
B. Differences:
The real values of value-type variables are directly stored in value-type variables.
The actual value (object) of the reference type is stored in the heap space. The variables of the reference type store the actual value (object) address in the space.
3. The value type and reference type have different values.
Here, we emphasize that no matter what type of variables are assigned to each other, the value of the source variable is copied in one copy and assigned to the target variable.
A. When values are assigned to each other, the value of one variable is modified without affecting the value of the other variable.
B. variables of the reference type are assigned values to each other. Two variables of the reference type actually point to the address (object) in the same heap space. Modifying one variable will affect the other variables.
Note: string is a special type of reference, which is stored in memory according to the reference type. however, this is not the case when assigning values, because of the constant character of the string.
4. Use the code to learn more about the differences between value types and reference types.
Int temp;
Temp = 100;
Console. WriteLine ("before modification, temp =" + temp );
ChangeValue (temp );
Console. WriteLine ("modified, temp =" + temp );
Student stu = newStudent () {Name = "James", Age = 30 };
Console. WriteLine ("before modification:" + stu. Name + ":" + stu. Age );
ChangeValue (stu );
Console. WriteLine ("modified:" + stu. Name + ":" + stu. Age );
Console. ReadKey ();
Static voidChangeValue (int num)
{
Num = 200;
}
Static voidChangeValue (Student stu)
{
Stu. Age = 40;
Stu. Name = "Li Si ";
}
Result:
5. The following figure shows the case above.
I believe that through this image example, you should understand the difference between the value type and the reference type!