c# – Where are class variables stored


After all, a class is a reference type, and variables in a class can be types by value. For instance:

class Car
    public int maxSpeed;       
    public Car(int max)
       maxSpeed = max;

Where is maxSpeed stored – on the stack or on the heap?


The question itself is caused by two problems

  • a fairly common, but generally incorrect statement "value-type variables are stored on the stack"
  • a little confusion in terminology – class fields are not "variables" – not local variables.

The point is that at the C # language level there is no concept of "stack" and "heap". There are two kinds of types:

  • Reference. The value of a variable or field of a class of this type stores the memory address at which an instance of the type is located. The instance itself is usually in the heap. An example is strings.
  • Value-types The value of a variable or class field stores the value directly. An example is int.

The concept of a stack is at the .NET / IL level. Local variables in IL .NET layer methods are stored on the stack. A C # variable does not always turn into an IL method variable. This happens if:

  • there are no closures to it
  • it is declared in a non-async method
  • there are still many different conditions caused by the implementation peculiarities of a particular C # compiler.

Type fields are stored as part of the type instance itself. They physically lie in the piece of memory that is allocated for a specific instance of the type. Those. if the instance itself is on the stack (for example, it is an instance of a structure), then the field is stored on the stack. If the instance is in the heap, then the field is also in the heap.

Specific examples

  • The method declares int a – it lies right on the stack
  • The method declares string s – the variable on the stack contains the address of the string in the heap.
  • The method declares Car c – the address of the Car object is in the variable on the stack. The object itself lies on the heap. Part of the object in the heap is the maxSpeed ​​field, which contains the speed value.
  • The method declares int [] arr – the address of the array in the heap is in the variable on the stack. The values ​​of individual cells lie directly in the array object in the heap.
  • A Point structure with X / Y fields is declared. The variable Point p is declared in the method – the structure itself, with all the fields, is in the variable on the stack.
Scroll to Top