Heaps, like mentioned in the previous page, deal
primarily with reference types, and one popular
reference type that you may already be familiar with is
a class. To best explain how the heap
works, let me first show you an example:
- class
Simpsons
- {
- public
string
name;
- public
int
age;
- }
-
- public
void
People()
- {
- Simpsons
bart
=
new
Simpsons();
- bart.name
=
"Bart";
- bart.age
=
10;
- }
The above code has a class called Simpsons, and the
Simpsons class has two public fields called
name
and age. You access the Simpsons class
via your People method, and inside your People
method, you both create a
bart object of type
Simspons
and initialize the bart object's name
and age fields.
Now that you an idea of what the code does, let's
take a look at how both our stack and heap look like
after running the People method:
Your stack, like before, contains the People
method call, and it includes an entry for
bart. Notice
that bart isn't pointing to a value,
but instead it is referencing
the Simpsons object on the heap. The reason is that
Simpsons is a class aka a reference type, and like
I mentioned before, reference types usually belong on
the heap.
After your People method has finished running, your
stack would once again be empty since it only contains
information on code that is or will be running. With
nothing left to run, our stack will be empty. The heap,
on the other hand, can still contain data:
In such a situation, you will
have something called a Garbage Collector that
goes through and clears unreferenced/unused data from
the heap. For example, the Simpsons class above would be
removed because it is no longer being used, and you will
end up with an empty stack and heap. I should clarify
that in most scenarios, when your application is more
complicated than the example presented in this post, you
may have some data from other methods taking up space in
both your stack and heap.
Onwards to the
next
page!