The CLR supports two types: reference type and value type
For reference types, you have to know:
- Memory must be allocated from the managed heap
- Each object allocated on the heap has some extra members that must be initialized
- Other bytes in the object are always set to zero
- Garbage collection may be enforced when an object is allocated from the managed heap
What you need to know about value types:
- Lightweight type
- Generally allocated on the thread stack (sometimes also embedded as a field in the object of the reference type)
- A value type instance variable does not contain a pointer to an instance, and the variable contains the field of the instance itself
- Instances of value types are not controlled by the garbage collector
Value types can sometimes provide better performance, specifically the type should not be declared as a value type unless all of the following conditions are met.
That is to say, consider declaring a type as a value type if all of the following conditions are true:
- Type has the behavior of primitive types. That is, a very simple type, no member will modify any instance fields of the type
- Types do not need to inherit from other types, nor do they derive any other type (because value types are implicitly sealed)
Another type of instance size is also under consideration,
Because the arguments are passed by default by value, the performance is affected by the replication of the fields in the value type instance.
A method that is also defined to return a value type when returned, the field in the instance is copied to the memory allocated by the caller, which affects performance.
Therefore, in order to declare a type as a value type, you must satisfy any of the above criteria:
- Small instances of type
- Type is large (but not passed as a method argument and not returned from the method), remember
When do I use value types? When do I use reference types?