How Garbage collector Will behave on value type and Reference type

How Garbage collector Will behave on value type and Reference type, when it will free memory value type and reference type. i am little bit confused about this can anyone explain about this, at the same time garbage collector remove free the Memory of value type or Reference type Which remove first

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re thinking about the problem the wrong way. Stop thinking about “value types” and “reference types”. Instead, start thinking about variables, and whether those variables are short lived or long lived.

The purpose of the garbage collected heap is to reclaim the storage associated with long-lived variables. The purpose of the stack is to reclaim the storage associated with short-lived variables.

People will try to tell you that “value types go on the stack” and “references go on the heap” and so on, and this is confusing nonsense. Variables go on the stack or the heap (or registers — everyone forgets about registers) and variables can be of value type or reference type.

You keep asking “which will the garbage collector remove first?” That question cannot be answered. The garbage collected heap makes no guarantees whatsoever about the order in which memory is reclaimed. The short-lived storage — the stack — will be reclaimed as activation frames are popped off the stack. However, the C# language permits the garbage collector to clean up storage that is referenced by short-lived storage before the frame is popped off the stack if the runtime can determine that the reference will not be accessed again. Basically, when storage is reclaimed is an implementation detail of the runtime, subject to change at any moment.

Method 2

The garbage collector is concerned only with reference types. It does not do anything whatsoever with value types.

Value types may live on the stack, in which case their memory is reclaimed when a method exits and the stack pointer is adjusted. Value types may also live on the heap as fields of reference types. In that case, the memory is reclaimed when the reference-type object is collected by the GC.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x