The allocation of reference types is quite complex. This blog post only describes the differences between the two instantiation methods.
Static void Main (string [] args) {Customer customer1; customer1 = new Customer ();}
Customer customer1;
Declare a Customer reference customer1 and allocate storage space to this reference on the stack. However, this is only a reference, not the actual Customer object. customer1 reference occupies 4 bytes of space (GetHashCode () returns an int type ).
Customer1 = new Customer ();
This line of code completes the following operations: First, it allocates memory to store the Customer object (a real object, not just an address ). Then, set the value of customer1 to the internal address assigned to the new Customer object (it will call the fields in the initialization class of the currently called constructor ). The Customer instance is not stored in the stack, but in the heap. Assuming that the current new Customer () object occupies 32 bytes, the. NET Runtime Library selects an unused, 32-byte continuous block in the heap.
Static void Main (string [] args) {Customer customer1 = new Customer ();}
This operation merges the preceding two steps into one step for execution.
Another problem is:
Static void Main (string [] args) {Customer customer1; Customer customer1 = null ;}
What are the differences between the two methods.