Let's say I have the following program:
public class Wallet
{
private int _money;
public Wallet(int money)
{
_money = money;
}
}
public class Person
{
private string _name;
private Wallet _wallet;
public Person(string name)
{
_wallet = new Wallet(0);
_name = name;
}
}
class TestClass
{
static void Main(string[] args)
{
var person = new Person("Toto");
}
}
If I understood well:
- The reference to
personwill be stored on the stack - The members held by a referenceType are stored on the heap so the mebers of
Personwill be stored on the heap, so_nameand_wallet - As
_moneyis hold byWallet, it would be stored on the heap too
I was wondering if actually, the reference of _wallet would be stored on the stack too, then _money and _name on the heap.
Is that correct ?
PS: Normaly I would inject Wallet but it would not be appropriate for my question.
The
personreference is a local variable so it goes in the call stack. An instance property like_walletis not a local variable so it goes in the heap because it belongs to the whole class.