Where are stored referenceTypes hold by referenceTyes in C#?

65 Views Asked by At

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:

  1. The reference to person will be stored on the stack
  2. The members held by a referenceType are stored on the heap so the mebers of Person will be stored on the heap, so _name and _wallet
  3. As _money is hold by Wallet, 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.

2

There are 2 best solutions below

0
beautifulcoder On

The person reference is a local variable so it goes in the call stack. An instance property like _wallet is not a local variable so it goes in the heap because it belongs to the whole class.

2
Guru Stron On

First of all The Stack Is An Implementation Detail, Part One (Part Two).

As for what is stored where - memory allocated to store reference types's data/info (in current CLR implementation) is stored on the heap, this includes fields (and backing fields for properties) both of value and reference types, the difference will be what is stored in the memory allocated for the object on heap (for value types it would be value itself, for reference - reference to another object on heap).

So in this case reference stored in _wallet will be on heap as the object this field references.

Read also: