Heap - this is the area of memory in which objects are located.
Heap constantly checked
garbage collector.
Garbage collector removes objects from memory that are not needed.
Data for
reference types are created in heap during program execution.
C#
class Program
{
static void Main(string[] args)
{
Calculate(10);
}
static void Calculate(int param1)
{
string text1 = "Hello";
int x = 6;
int y = x + param1;
}
}
Method
Calculate(10) Is:
All the variables, and these are:
param1,
text1,
x,
y will be added to stack.
• Variable
param1. value of variable
param1 This is 10 is placed in stack (
int -
value type)
• What happens to a variable
text1? (
string -
reference type)
In the
stack is put reference to
heap
In the
heap put the value "Hello"
• Variable
x. value of variable
x This is 6 is placed in stack (
int -
value type)
• Variable
y. value of variable
y This is 16 is placed in stack (
int -
value type)
C#
struct Place
{
public int x = 45;
public int y = 67;
}
class Book
{
public int Name = "Fantastic";
public int Price = 20;
}
class Program
{
private static void Main(string[] args)
{
Place place1 = new Place();
Book book1 = new Book();
}
}
When
reference type object ceases to be used,
then the link is removed from the stack.
Thereafter
garbage collector verifies that there are no references to our object and removes the object from heap.
{
public int x = 45;
public int y = 67;
// structures need constructors
// while such initialing is prohibited ! Check it out by yourself !
}
class Book
{
public int Name = "Fantastic";
// that's a typo : string type instead...
public int Price = 20;
}