c reference types and value types

  • 2020-05-07 20:19:05
  • OfStack

CLR supports two types: reference types and value types.
Reference types are always assigned from the managed heap.

The New operator in c# returns the memory address of the object.

Points to note about reference objects:

1. Memory is allocated from the managed heap
2, allocation of objects on the heap, there are 1 some additional operations, affect 1 some performance
3. When an object is allocated from the managed heap, one garbage collection may be enforced.

The value types in CLR are lightweight. No need to pick up 1 pointer, no need for garbage collection, can reduce the number of garbage collection.
In CLR, all the "classes" are reference types, and all value types are called structures or enumerations.
All structures are directly derived from the abstract class ValueType. ValueType is directly derived from Object.
All enumerations are derived from the Enum abstract class, and Enum is derived from ValueType.

One value type can implement one or more interfaces, but it cannot inherit from the base class. All value types are implicitly sealed.

c# declares structures with struct and classes with class.

The value type should satisfy:

1. Types have primitive types
2. A type does not need to be inherited from any other type
3. Not as a base class
4. Type size should not exceed 16k

Differences between value types and reference types:

1. You cannot use a value type as a base type
2. The reference type variable contains an object address on the heap. The value type is the value object itself.
3. When the value type is assigned, a field-by-field copy will be performed. When the value of the reference type variable is assigned, only the memory address will be copied.
4. Multiple variables of reference type may refer to the same object in the heap, and the value type is a body of its own without affecting each other.

Related articles: