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?
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?
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.)
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.