I'm refreshing my memory on how reference and value types work in .NET. I understand that the entry on the stack for a reference type contains a pointer to a memory location on the heap. What I can't seem to find details about is what else the stack entry contains. So, given the following:
Customer customer;
customer = new Customer();
After the first line of code an entry on the stack containing a null pointer will exist. Does that entry also contain the identifying name "customer"? Does it contain type information?
Have I fundamentally misunderstood something?
Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . For reference types, the reference is stored on the stack while the object it refers to is stored on the heap. For value types, the object itself is stored on the stack.
Examples of reference types include: strings, arrays, objects of classes, etc.
A reference type variable contains a reference to data stored in memory, also known as the heap. The heap is most often used for data that has a longer life. You can have more than one variable point to the same referenced data. Objects are an example of a reference type.
Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.
Only the pointer to the object is stored, nothing else. Not on the stack, it is stored in a processor register. Only if the method is large and the register is better used for other purposes will it be stored on the stack. Making that the decision is the job of the optimizer. Which is in general fairly unlikely to happen since you'll probably be using properties and methods of the Customer class so keeping the pointer in a register is efficient.
This is otherwise the basic reason why a NullReferenceException can tell you nothing useful about what reference is null. Associating the pointer value back to a named "customer" variable can only be done by a debugger. It needs the PDB file to know the name of the variable, that name is not present in the metadata of the assembly. Which is the basic reason why you cannot use Reflection to discover local variable names and values.
And this is also why debugging only works well when you use it on the Debug build of your project. That disables the optimizer and gets the pointer value to always be stored back to a stack slot, allowing the debugger to reliably read it back. At a significant cost, the basic reason you should only ever deploy the Release build of your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With