When operator new() is used with reference type, space for the instance is allocated on the heap and reference variable itself is placed on the stack. Besides that, everything within the instance of reference type, that is allocated on the heap, is zeroed-out.
For example here is a class:
class Person
{
public int id;
public string name;
}
In the following code:
class PersonDemo
{
static void Main()
{
Person p = new Person();
Console.WriteLine("id: {0} name: {1}", p.id, p.name);
}
}
p variable is on the stack and the created instance of Person (all of its memebers) is on the heap. p.id would be 0 and p.name would be null.
This would be the case because everything allocated on the heap is zeroed-out.
Now what I'm confused about is if I'm using a value type with new operator. For example, take into consideration following structure:
struct Date
{
public int year;
public int month;
public int day;
}
class DateDemo
{
static void Main()
{
Date someDate;
someDate= new Date();
Console.WriteLine("someDate is: {0}/{1}/{2}",
someDate.month, someDate.day, someDate.year);
}
}
Now I would like to know what do the following lines from main do:
Date someDate;
someDate= new Date();
In first line someDate variable is allocated on the stack. Precisely 12 bytes.
My question is what happens on the second line? What does operator new() do? Does it only zero-out members of Date structure or it allocates space on the heap as well? On one side I wouldn't expect new to allocate space on the heap, of course because in the first line memory is already a