SoFunction
Updated on 2025-03-01

c# reference type and value type

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

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

Notes on referencing objects:

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

The value types in CLR are lightweight. There is no need to withdraw a pointer, and there is no need to garbage collection, which can reduce the number of garbage collections.
In CLR, what is generally called "class" is a reference type, and all value types are called structures or enums.
All structures are direct derived classes of the abstract class ValueType. ValueType is derived directly from Object.
All enums are derived from the Enum abstract class, which in turn is derived from ValueType.

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

In C#, use struct to declare structure and class to declare classes.

The value type should satisfy:

1. Types have primitive types
2. Types do not need to be inherited from any other type
3. Not used as a base class
4. The size of the type should not exceed 16k

Differences between value types and reference types:

1. The value type cannot be used as the base type
2. The reference type variable contains an object address on the heap. The value type is the value object itself.
3. When value type assignment is assigned, field-by-field copying will be performed. When reference type variable assignment is assigned, only the memory address will be copied.
4. Multiple variables of reference types may refer to the same object in the heap. The value types are self-organized and have no influence on each other.