The difference between reference types and value types is often confusing for beginners due to not understanding what a variable of value type actually holds. We know that:
- Value types store the actual value
- Reference types only store the reference to the object
Is it possible to inspect each kind of variable to either see the value, or the actual reference itself? Is the reference stored as some kind of coded value? I know that references can be passed by value so I’m assuming so.
I think this would help newcomers with their understanding, and be very interesting to explore.
Just to clarify, the value of a variable of reference type is a reference. The reference is the value.
A reference is a kind of value, just like an int is a kind of value. Unlike an int, a reference is a value that can only be copied and dereferenced; you cannot observe its value directly in C#, because its value is an implementation detail of the garbage collector.
Yes, exactly. In practice, a reference is a 32 or 64 bit integer (depending on whether you are in a 32 or 64 bit process) that is a pointer to some structure known to the garbage collector as being associated with the data of the referred-to object.
If you want to look at references directly, the tool to do so is the debugger. Load your C# code into the debugger, compile it, run it, hit a breakpoint, and take a look at the state of the stack and registers. With a little cleverness you should be able to figure out which stack locations and registers correspond to which local variables. The locations corresponding to local variables of value type will contain the values; those of reference type will contain values that look like pointers. If you examine those pointers in the memory window, you will then be looking at the structures maintained by the garbage collector that describe the contents of the object.