C# memory use during instatiation

I am trying to understand how classes work in C#. When I instantiate a class does that make a copy of the class or does it just point to one. Also how does it handle if I use the class (instantiate) more than one. Is a copy made for each time I instantiate? And how does it keep the variables defined in the class separate for each instantiate copy?

1 Like

Hi,

  • When a class is instantiated in C# the instance of the object gets allocated to the heap (this is dynamically-allocated memory, as in, it can grow and shrink in size).
  • The variable itself acts as a reference to the address of that same object (this variable goes on the stack).
  • If you instantiate multiple classes, you’re allocating more unique objects on the heap. By unique I mean, they do not share data (changing one does not change the other, the objects don’t have shared-memory access).
  • Again, all the different objects you instantiate will have their variable stored on the stack (it acts as a reference to the respective address on the heap, otherwise you wouldn’t have access to the object itself).

I highly recommend Hennessy and Patterson’s book on Computer Organization if you want to know more in-depth.

Here’s the documentation on the C# implementation: Objects - create instances of types | Microsoft Docs

Link on basic memory management: Memory Management/Stacks and Heaps - Wikibooks, open books for an open world

1 Like

Thanks. That does help. I do have another question. If I have one class and I instationate it 3 times. (Var1, Var2, Var3). Will a copy of the class be stored in memory 3 times with 3 reference variables? (Var1, Var2, Var3) or will there only be one copy of the class in memory with 3 references one for each Var variable?

Hi,

The program code in generally stored in a place called the text segment. This would include all your class and method definitions. Strictly speaking when a class is instantiated the object data goes into the heap (at least in C#). So if you do it 3 times there will be 3 allocations of memory on the heap for each instantiation. Additionally, 3 variables will be pushed onto the stack that relate to these objects. Your text segment does not change during the running of the program.

(Well, this is a bit of a simplification because C# is not compiled to a binary directly, so the actual process in C# might be slightly more involved, but big-picture this is roughly it)

A visual (source: Processes)