Value and Reference Types and the Memory

Taylor Emma
1 Min Read
Disclosure: This website may contain affiliate links, which means I may earn a commission if you click on the link and make a purchase. I only recommend products or services that I personally use and believe will add value to my readers. Your support is appreciated!

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.

Share This Article
A senior editor for The Mars that left the company to join the team of SenseCentral as a news editor and content creator. An artist by nature who enjoys video games, guitars, action figures, cooking, painting, drawing and good music.
Leave a review