It defines the type of data stored in the data memory size and composition of the type required data members. Type also determines the position of the object is stored in memory - the stack or heap.
They are classified into two types: value types and reference types and both types of objects are stored in memory.
- It takes a value of only a single type of memory to store the actual data.
- It requires two memory reference type.
- The first paragraph of the actual data storage, which is always heap.
- Second is a reference to the data storage position in the stack.
The following figure shows how each type of single data items are stored. For the type of value, the data stored in the stack. For reference types, the actual data stored on the heap and referenced stored on the stack.
Value Type
All value types are implicitly derived from System.ValueType
the following table shows the value of C # Type:
Value Type | category | Type suffix |
---|---|---|
bool |
Boolean |
|
byte |
No symbols, numbers, integer | |
char |
No symbols, numbers, integer | |
decimal |
Numbers, floating point | M or m |
double |
Numbers, floating point | D or d |
enum |
enumerate | |
float |
Numbers, floating point | F or f |
int |
With symbols, numbers, integer | |
long |
With symbols, numbers, integer | L or l |
sbyte |
With symbols, numbers, integer | |
short |
With symbols, numbers, integer | |
struct |
User-defined structures | |
uint |
No symbols, numbers, integer | U or u |
ulong |
No symbols, numbers, integer | UL , Ul , uL , ul , LU , Lu , lU Orlu |
ushort |
No symbols, numbers, integer |
Value type contains the value directly, in other words, the variable position is a position reference value is actually stored in memory.
Thus, assigning a value to a variable, then the variable 1 to the variable 2, copies the value of the variable in the 2 position to create, rather than a reference to a variable position.
This further causes the value of the variable changes will not affect the value of the variable 1 of 2.
The figure below demonstrates this. number1
Reference to a particular location in memory, that location contains a value 42
. The number1
value assigned to the number2
following two variables contain values 42
. But modify any one of these values will not affect another value.
Similarly, the passed value type instances Console. WriteLine()
such methods will generate a memory copy. Any changes to the parameter values inside the method will not affect the original value of the calling function.
Reference types
引用类型的变量存储对数据存储位置的引用,而不是直接存储数据。要去那个位置才能找到真正的数据。所以为了访问数据,“运行时”1 要先从变量中读取内存位置,再“跳转”到包含数据的内存位置。
为引用类型的变量分配实际数据的内存区域称为堆(heap)。
由于引用类型只拷贝对数据的引用,所以两个不同的变量可引用相同的数据。因此,对一个变量执行的操作会影响另一个变量所引用的对象。无论赋值还是方法调用都会如此。因此,如果在方法内部更改引用类型的数据,方法执行完成之后,将看到更改后的结果。
总结
一个类型要么是值类型,要么是引用类型。区别在于数据存储的方式:对于值类型,数据存放在栈里。对于引用类型,实际数据存放在堆里而引用存放在栈里。
引用类型的变量存储对其数据(对象)的引用,而值类型的变量直接包含其数据。 对于引用类型,两个变量可引用同一对象;因此,对一个变量执行的操作会影响另一个变量所引用的对象。 对于值类型,每个变量都具有其自己的数据副本,对一个变量执行的操作不会影响另一个变量。