C # reference type and value type,
C # reference type and Value Type
CLR supports two types: reference type and value type.
1. Reference Type
(1) The memory must be allocated from the managed stack;
(2) Each object allocated on the heap has some additional members (including "type Object Pointer" and "synchronous block Index"), which must be initialized;
(3) Other bytes of the object are always set to zero;
(4) When allocating objects from the managed heap, a garbage collection may be executed forcibly.
2. Value Type
(1) generally allocated on the thread stack;
(2) not controlled by the garbage collector;
3. Differences between the two
(1) Two representation forms of the Value Type: unpacked and boxed, the reference type is packed;
(2) The value type is derived from System. ValueType. It provides the same method as System. Object, but overwrites the Equals and GetHashCode methods;
(3) because the value type cannot be the base type, virtual methods should not be used in the value type;
(4) The reference type contains the address of the object in the heap. The default value is null;
(5) assign a value type variable to another value type variable. The value of each field is copied, while the reference type only copies the memory address, therefore, copying objects that change the value type does not affect the original value, but the reference type changes the original value;
(6) because the unencapsulated value type is not allocated on the heap, the memory will be released if this type of case is no longer active after allocation.
4. Packing
Definition: converts a value type to a reference type.
(1): In the heap memory, allocate the memory required for each field of the Value Type plus the memory required for additional members (type object pointers and synchronized block indexes;
(2): Copy fields of the value type to the newly allocated pair memory;
(3): return the object address.
5. binning
Definition: converts a reference type to a value type.
(1): Obtain the Field Values of boxed cases;
(2): Type of the value in the field copied from the heap to the stack.
Note:
(1): If the reference of the boxed case is null, an NullReferenceException exception is thrown;
(2): If the referenced object is not a boxed instance of the required value type, an InvalidCastException is thrown.
For example:
1 public static void Main()2 {3 Int32 x = 5;4 Object o = x; 5 Int64 y = (Int64) (Int32) o;6 }