C #: from the basics to the medium level [Reference type vs Value type (Part II)]

Matteo Lo Piccolo
3 min readAug 6, 2021

--

Now, let’s look what’s happen when we use the Reference type.
For example, I create an Array, because Array is a class.
Then I copy the Array on another Array, and make some modification, for example we can set the first element to 0

Now, what you think is the value of first element of firstArray?
Is ZERO.

Why?
Let’s try to explain what happen behind the scene.

When we create the firstArray, is allocated in the HEAP MEMORY, with a memory address.
Then in the STACK MEMORY, we have the variable to identify this Array.
Inside this variable, we have a MEMORY ADDRESS, which is the address of the object in the HEAP.

So we can say that variable POINTS to the Array in the Heap.

But what happen when we copy firstArray on secondArray?
At Runtime, or CLR, we create second variable in the STACK, which has THE SAME MEMORY ADDRESS OF firstArray, so they literally point in the same place in the HEAP where we have our Array.

This means that every change to the Array is absolutely visible through the variables we created to reference it.

Let’s try in code and see…

…and they have same element zero

Make another example, just to understand better

I have a Enemy class with Life field, and two methods, one for increment the number, one for increment life.
Both of this method have one parameters, a value type int and a reference type enemy.
And both are static only because are easy to access without create an object (in the class section we will talk more about it).

Now, I create a number variable inside Main, call AddNumber and pass the number as paremeter inside it.

What you think is the value of number?
Is ONE.
Why this?
Because even if the variables have same name, they live in two complete different place in memory.

The number we see above has his SCOPE ONLY IN THE MAIN METHOD, outside is literally “useless”.
At the same, the number inside AddNumber is created when we call the method, it add 10 to its value, and is IMMEDIATLY DESTROYED.
Because that “number” lives only inside that method.

Let’s try

And the number is 1.

Now, back to our Enemy class (Reference type).
If we now create an Enemy object and set its life to 90

The difference here is that enemy object we created and and enemy parameter of AddLife(Enemy enemy) point AT THE SAME MEMORY ADDRESS IN THE HEAP.

So if we call AddLife() and pass enemy object

And the enemy.Life is 100.

--

--

Matteo Lo Piccolo
Matteo Lo Piccolo

Written by Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!

No responses yet