5

I understand there is garbage collection for reference types, but I'm wondering how garbage collection works for value types.

Do value types get garbage collected when they go out of scope?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • possible duplicate of [Do value types get Garbage collected?](http://stackoverflow.com/questions/2342772/do-value-types-get-garbage-collected) – nawfal Jul 16 '14 at 10:54

2 Answers2

10

Only storage allocated on the heap has to be garbage collected.

If a value type variable is on the heap, it's either part of some other class, or a boxed value, which is an object which only contains the value type value. The value is part of the memory which is "freed" when the containing object is garbage collected.

If a value type variable is on the stack, the memory it uses will be effectively "freed" when the stack frame is popped by the method returning.

Note that what ends up on the stack and what ends up on the heap is an implementation detail which is made more complicated by captured variables, iterator block, async methods, ref parameters etc. But the broad principle is that the memory used for value type values are always part of "something else" - so the it's reclaimed when the memory for that "something else" is reclaimed. (This isn't some sort of separate step - the value lives within the memory for that "something else" whether it's an object or a stack frame.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
-1

Value types are stored on the stack. That means, that runtime keeps pointer to the top of the stack for each method, and when you return from method, this top will be moved down. Making any variables declared in this method out-of-scope.

For a class fields, those are stored in memory of concrete class and are garbage-collected as part of the class itself.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • We are talking about local variables in methods according to "when a variable of value type goes out of the scope". All of those are stored on the stack. – Euphoric Jun 28 '11 at 05:17
  • @Euphoric: Not all variables are parameters. The OP is not asking specifically about parameters; there are multiple other ways a variable can go out of scope. – Esteban Araya Jun 28 '11 at 05:20
  • @Esteban Araya: I'm not talking about parameters. I'm talking about local variables. – Euphoric Jun 28 '11 at 05:26
  • 1
    @Euphoric: Local variables aren't always stored on the stack. Think about iterator blocks and captured variables... and it's all implementation-specific. – Jon Skeet Jun 28 '11 at 05:27
  • @Euphoric: What if a local variable value type is boxed? Where does that go? – Esteban Araya Jun 28 '11 at 05:31