Understand the difference between a value type and a reference type

  • 2020-05-19 04:35:59
  • OfStack

The difference between:
1. The value type is usually assigned on the stack, and its variables directly contain the instance of the variable, which makes it more efficient to use.
2. The reference type is allocated on the managed heap. A variable of the reference type usually contains a pointer to an instance through which the variable references the instance.
3. The value type is inherited from ValueType (note: System.ValueType is inherited from System.Object); The reference type is inherited from System.Object.
4. Value type variables contain instance data, and each variable keeps its own copy (copy) of the data. Therefore, by default, the parameter transfer of value type does not affect the parameter itself. The reference type variable holds the reference address of its data, so passing the parameter by reference affects the parameter itself, since both variables reference the same address in memory.
5. There are two types of value: packing and unpacking; The reference type has only one form of boxing. I'll discuss this topic in more detail in the next section.
6. Typical value types are struct, enum and a large number of built-in value types; Anything that can be called a class is a reference type.
7. The memory of the value type is not controlled by GC (garbage collection, Gabage Collection). At the end of the scope, the value type will be released by itself, which reduces the pressure on the managed heap and thus has a performance advantage. For example, struct is generally more efficient than class; The reference type of memory recycling, which is done by GC, is even recommended that users do not free up memory on their own.
8. The value type is hermetically sealed (sealed), so the value type cannot be used as a base class for any other type, but can be inherited as a single or multiple interface; The reference type 1 is generally inherited.
9. Value type does not have polymorphism; The reference type is polymorphic.
10. The value type variable cannot be null value, and the value type will be automatically initialized to 0 value; By default, the reference type variable is created as an null value to indicate that there is no reference address pointing to any managed heap. Any operation on a reference type whose value is null throws an NullReferenceException exception.
11. There are two states for value types: boxed and unboxed. The runtime provides boxed forms for all value types. The reference type usually takes only one form: boxing.

Related articles: