Yesterday, we had a discussion on Gargbage collection.
It was discussed that the objects created using Classes are collected by Garbage collector, but it cannot be collected by GC if it is being created using struct
I know that structures uses stack and classes uses heap.
But, I guess GC never collects unmanaged codes only. So does that mean that the Structure types are unmanaged code. (I don’t think so).
OR is it that the GC take care of Heap only and not Stack?
If yes, then what about int data type. int is struct not class. So if we defined the object of type int, isn’t it managed by GC?
The GC will collect any managed objects (and Structures are managed objects) if they cannot be accessed from a GC root.
What you were told is incorrect. It doesn’t matter how a managed object was created – if there are no references to it anymore, it will end up being collected.
The GC takes care of the object graph – if objects are reachable by any of the GC roots, they will not be collected, if they are not, they will end up being collected. The Stack and Heap are not relevant.
int(AKASystem.Int32) is a managed object – a structure. If you declare anintfield in a class and the class goed out of scope, theintwill end up being collected by the GC, for example.As @leppie commented, in many situations, structures will get placed on the stack and when the stack is popped they will no longer exist – the GC, in such cases, is not involved (and doesn’t need to be).