In this example we will illustrate how value and reference types are represented in memory. Consider the execution of the following programming code:
As you can see from the figure, a change in a value type (i = 0) changes its value directly into the stack. When changing a reference type, things are different: the value is changed in the heap (bytes[1] = 0). The variable that keeps the array reference remains unchanged (0x00190D11). When assigning a null value in a reference type, that reference is disconnected from its value and the variable remains with no value (obj = null).
When assigning new value to an object (a reference type variable) the new object is allocated in the heap (the dynamic memory) while the old object remains free (unreferenced). The reference is redirected to the new object (str = “Bye”) while the old objects (“Hello”) will be cleaned at some moment by the garbage collector (the .NET Frameworkâs internal system for automatic memory cleaning) as they are not in use anymore.
Comments are closed.