Value Types & Reference Types ( Why Pointer?)

April 20, 2020

Value types have exact amount of memory space they take up.
On the other hand Reference types have dependency of amount of data they store, based on that they extend memory space by using pointers.

It’s always 32 bits of memory for int data type, regardless of data:

boolean, character, float, double, int, long, decimal are value types

But why we don’t allocate memory consecutively for reference types and why we need pointers?
Assume we have two collections:

Now if we keep allocated memories consecutively for adding a new member in Collection A we will override Collection B’s first element:

This means by storing data consecutively in data structures, we risk overwriting and losing precious data. How can we solve this? We can use something called pointers.
Instead of storing the entire data structure directly in a set of consecutive bits, we’ll create an address that will point to where the structure, or sometimes part of the structure is in memory. Since we use a reference to find where the data lives in memory we call strings and other data types implemented with data structures reference types.

Leave a Reply:

Your email address will not be published. Required fields are marked *