Personal understanding of value types and reference types in C #

In addition to ultimately inheriting from Object, value types also inherit from ValueType

Value types inherit from ValueType, and ValueType inherits from Object. (All types in c# ultimately inherit from Object)

When creating a reference type, runtime will allocate two spaces for it, a space is allocated on the heap, To store the data of the reference type itself, another block of space is allocated on the stack to store a reference to the data on the heap (the memory address on the heap actually stored, that is, the pointer).

When creating a value type, runtime will allocate a space for it. This space is allocated in the place where the variable is created, such as:

If the value type is in Method is created internally, then follow the method to the stack, and allocate it to the stack for storage.

If the value type is a reference type member variable, follow the reference type and store it on the heap.

Value type data is stored in the memory stack; reference type data is stored in the memory heap, and the memory unit only stores the objects in the heap

Value type access speed is fast, while reference type access speed is slow.

Value type represents actual data, and reference type represents a pointer or reference to data stored in the memory heap

Stack The memory allocation of is automatically released; and the heap will be released by GC in .NET

Value type variables directly store the value of the variable on the stack, and reference type variables will The address of the actual data is stored in the stack, and the actual data is stored in the heap

For example: int is a value type, string is a reference type, and a reference type points to the heap Location

Leave a Comment

Your email address will not be published.